How to attach a jquery autocomplete to input element

倖福魔咒の 提交于 2021-01-28 13:19:41

问题


I want to attach autocomplete to jquery input element. I downloaded jquery widget v1.12.1 ( only autocomplete) from this link enter link description here.

function maintest () {
        let table;
        let row1;
        let row2;
        let cell0;
        let cell1;
        let header2;
        let autocomplete1;
        
        table = $('<table>');
        table.attr({"id":"testtable"});
     
       
        row1 = $('<tr>');
        table.append(row1);
        header2 = $('<th>').text("Feature/Description");
        row1.append(header2); 
     
        row2 = $('<tr>');
        table.append(row2);
     
        cell1 = $('<td>');
        row2.append(cell1); 
        autocomplete1 = $("<input>").attr({"id" : "selector0"});
        /*$("#selector0").autocomplete( "option", "source", [ "c++", "java", "php", "coldfusion", "javascript", "asp",              "ruby" ] );
        cell1.append(autocomplete1);*/
     
        $("#mainDiv").append(table);


 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="maintest()">
  <div id="mainDiv"></div>
</body>

Note :I have commented the autocomplete beacause I didn't find proper cdn to include jquery widget for autocomplete

My requirement is to add autocomplete to input box


回答1:


It looks like you need to add the autocomplete before you call options on it. Here's a working CodePen version: https://codepen.io/edlucas/pen/mdJejqo

function maintest () {
        let table;
        let row1;
        let row2;
        let cell0;
        let cell1;
        let header2;
        let autocomplete1;

        table = $('<table>');
        table.attr({"id":"testtable"});


        row1 = $('<tr>');
        table.append(row1);
        header2 = $('<th>').text("Feature/Description");
        row1.append(header2); 

        row2 = $('<tr>');
        table.append(row2);

        cell1 = $('<td>');
        row2.append(cell1); 
        autocomplete1 = $("<input>").attr({"id" : "selector0"});
          cell1.append(autocomplete1);

        $("#mainDiv").append(table);
        $("#selector0").autocomplete();
        $("#selector0").autocomplete( "option", "source", [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ] );

}


来源:https://stackoverflow.com/questions/60194859/how-to-attach-a-jquery-autocomplete-to-input-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!