【问题标题】:Auto complete dynamically generated text box自动完成动态生成的文本框
【发布时间】:2016-05-30 09:52:10
【问题描述】:

我需要帮助来使用 jquery 自动完成填充动态生成的文本框。

工作流程:

1.单击添加行按钮时,将插入一行。

2.在插入的行上,产品文本框应该通过自动完成来填充。同样的方式所有动态生成的文本框都应该通过自动完成来填充

问题:

我已经使用jquery自动完成功能来填充文本框,但是自动完成功能只对第一行的文本框起作用。我需要通过自动完成功能来填充所有动态创建的文本框。

这是我的代码。

<html>
<head>
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script src="JS/jquery.autocomplete.js"></script>
<script>
jQuery(function(){
$("#product").autocomplete("Productset.jsp");
});
</script>

<script type="text/javascript">

        function addRow(tableID) {

            var table = document.getElementById(tableID);

            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);

            var colCount = table.rows[0].cells.length;

            for(var i=0; i<colCount; i++) {

                var newcell = row.insertCell(i);

                newcell.innerHTML = table.rows[1].cells[i].innerHTML;
                //alert(newcell.childNodes);
                switch(newcell.childNodes[0].type) {
                    case "text":
                            newcell.childNodes[0].value = "";
                            break;

                    case "select-one":
                            newcell.childNodes[0].selectedIndex = 0;
                            break;
                }
            }
        }

       function deleteRow(tableID) {

        try {

           var table = document.getElementById(tableID);

           var rowDelete = table.rows.length - 1;

           if (rowDelete > 1)

               table.deleteRow(rowDelete);

           else

             alert("Cannot delete all the rows.")
        }

        catch(e) {

            alert(e);
        }
    }
    </script>

</head>

<body>
<form>

      <input type="button" value="Add Row" onclick="addRow('dataTable')" />

    <input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

    <br/>
    <br/>

     <table id="dataTable" align="center" width="350px" border="1">

   <tr>
         <th> Product Name</th>
          <th>Quantity</th>
         <th> Brand</th>       

    </tr>

    <tr>

   <td> <input type="text" name="pname" id="product" value="" /></td> &nbsp;
   <td><input type="text" name="qty" value=""/></td>
    <td><select name="brand"/>
        <select>
           <option value="select">SELECT</option>

       </select>
    </td>
  </table>
</form>
</body>
</html>

Productset.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>

   <%
   try{
     String s[]=null;

     Class.forName("com.mysql.jdbc.Driver");
     Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/pdt","root","root");
     Statement st=con.createStatement();
     ResultSet rs = st.executeQuery("select distinct product from productlist");

       List li = new ArrayList();

       while(rs.next())
       {
           li.add(rs.getString(1));
       }

       String[] str = new String[li.size()];
       Iterator it = li.iterator();

       int i = 0;
       while(it.hasNext())
       {
           String p = (String)it.next();
           str[i] = p;
           i++;
       }

    //jQuery related start
       String query = (String)request.getParameter("q");

       int cnt=1;
       for(int j=0;j<str.length;j++)
       {
           if(str[j].toUpperCase().startsWith(query.toUpperCase()))
           {
              out.print(str[j]+"\n");
              if(cnt>=5)// 5=How many results have to show while we are typing(auto suggestions)
              break;
              cnt++;
            }
       }
    //jQuery related end

rs.close();
st.close();
con.close();

}
catch(Exception e){
e.printStackTrace();
}


%>

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    您需要在 jquery 'on' 函数中调用自动完成功能

    $(document).on("focus","#product",function(e){
     $(this).autocomplete("Productset.jsp");
    });
    

    【讨论】:

      【解决方案2】:

      当您添加新行时,您应该再次调用自动完成功能

      $("#button").click(function(e) {
          addRow();
           $(".auto").autocomplete({
            source: datas
          });
      });
      

      https://jsfiddle.net/w78L1ho2/

      如果您的 Productset.jsp 没有移动,我建议只调用一次。

      要使用文本文件填充数据,您可以执行以下操作 (将文本文件转换为数组来自https://stackoverflow.com/a/6833016/5703316):

        var datas = [];
      
        function func(data) {
          datas.push(data);
        }
      
        function readLines(input, func) {
          var remaining = '';
      
          input.on('data', function(data) {
            remaining += data;
            var index = remaining.indexOf('\n');
            var last = 0;
            while (index > -1) {
              var line = remaining.substring(last, index);
              last = index + 1;
              func(line);
              index = remaining.indexOf('\n', last);
            }
      
            remaining = remaining.substring(last);
          });
      
          input.on('end', function() {
            if (remaining.length > 0) {
              func(remaining);
            }
          });
        }
      
        $.get("Productset.jsp").done(function(result) {
          readLines(result, func);
        });
      

      【讨论】:

      • 此解决方案适用于默认数据集,但在我的情况下,数据来自数据库。那么如何处理呢?
      • 您必须执行 ajax 请求才能填写您的列表。像这样(取决于服务器结果)$.get("Productset.jsp").done(function(result){datas=result});
      • 除了使用ajax还有什么办法吗?我需要通过使用javascript从数据库(Productset.jsp)中获取数据来通过自动完成来填充文本框
      • 你可以设置自动完成的来源,就像这个例子:jqueryui.com/autocomplete/#remote,所以对你来说它将是$(".auto").autocomplete({ source: "Productset.jsp" });所以在我的小提琴中用“Productset.jsp”替换我的数据变量。
      • 当我尝试像这样jQuery(function(){ $("#product").autocomplete("Productset.jsp"); }); 时,仅第一个文本框通过自动完成填充,但是当我将代码更改为此jQuery(function(){ $("#button").click(function(e) { addRow(); $(".auto").autocomplete({ source: "Productset.jsp" }); }); 时没有任何反应,自动完成甚至没有反映在第一个文本框
      【解决方案3】:

      在我的代码中,动态创建的文本框不采用 jquery 自动完成功能。因此,在 addrow() 方法中包含自动完成功能将使用自动完成数据填充动态创建的文本框。

      id选择器只会用自动完成数据填充第一个文本框。所以在jquery函数中使用这个$('input[name="product"]').auto complete("Productset.jsp");来填充所有文本框。

      这是完整的代码。

      <html>
      <head>
      <script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
      <script src="JS/jquery.autocomplete.js"></script>
      <script>
      jQuery(function(){
      $("#product").autocomplete("Productset.jsp");
      });
      </script>
      
      <script type="text/javascript">
      
              function addRow(tableID) {
      
                  var table = document.getElementById(tableID);
      
                  var rowCount = table.rows.length;
                  var row = table.insertRow(rowCount);
      
                  var colCount = table.rows[0].cells.length;
      
                  for(var i=0; i<colCount; i++) {
      
                      var newcell = row.insertCell(i);
      
                      newcell.innerHTML = table.rows[1].cells[i].innerHTML;
                      //alert(newcell.childNodes);
                      switch(newcell.childNodes[0].type) {
                          case "text":
                                  newcell.childNodes[0].value = "";
                                jQuery(function(){
                      $('input[name="product"]').autocomplete("Productset.jsp");
                                       });
      
                                        break;
      
                          case "select-one":
                                  newcell.childNodes[0].selectedIndex = 0;
                                  break;
                      }
                  }
              }
      
          </script>
      
      </head>
      
      <body>
      <form>
      
            <input type="button" value="Add Row" onclick="addRow('dataTable')" />
      
          <input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
      
          <br/>
          <br/>
      
           <table id="dataTable" align="center" width="350px" border="1">
      
         <tr>
               <th> Product Name</th>
                <th>Quantity</th>
               <th> Brand</th>       
      
          </tr>
      
          <tr>
      
         <td> <input type="text" name="product" id="product" value="" /></td> &nbsp;
         <td><input type="text" name="qty" value=""/></td>
          <td><select name="brand"/>
              <select>
                 <option value="select">SELECT</option>
      
             </select>
          </td>
        </table>
      </form>
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-25
        • 2015-08-30
        • 2011-04-18
        相关资源
        最近更新 更多