如何将jQuery自动完成附加到输入元素

时间:2020-02-12 18:30:10

标签: javascript jquery html jquery-ui autocomplete

我想将自动完成功能附加到jquery输入元素。我从此链接enter link description here下载了jquery小部件v1.12.1(仅自动完成)。

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>

注意:我评论了自动填充功能,因为找不到适合自动填充功能的jQuery小部件的cdn

我的要求是在输入框中添加自动填充

1 个答案:

答案 0 :(得分:1)

您似乎需要添加自动完成功能,然后才能调用其上的选项。这是有效的CodePen版本: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" ] );

}