0

I need help in filling the dynamically generated text boxes using jquery autocomplete.

Workflow:

1.On clicking add row button a row will be inserted.

2.On the inserted row,the product text box should be filled through auto complete.The same way all the dynamically generated text boxes should be filled by auto complete

Issue:

I have used the jquery auto complete function to fill the text boxes,but the auto complete function is working only for the text box in the first row.I need to fill all the dynamically created text boxes through auto complete function.

This is my code.

<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();
}


%>
sound
  • 55
  • 2
  • 11

3 Answers3

0

You need to call autocomplete in jquery 'on' function

$(document).on("focus","#product",function(e){
 $(this).autocomplete("Productset.jsp");
});
Muthu
  • 432
  • 1
  • 3
  • 19
0

When you add a new row you should call again the autocomplete function

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

https://jsfiddle.net/w78L1ho2/

if your Productset.jsp is not moving I recommand to call it only once.

To fill your datas with your text file you can do something like this (convert text file to array comes from 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);
  });
Community
  • 1
  • 1
Quentin Roger
  • 6,410
  • 2
  • 23
  • 36
  • This solution is working fine for the default set of data, but in my case the data is coming from the database.So how to handle that? – sound May 30 '16 at 10:42
  • You must do an ajax request to fill your list . With something like this (depending on the server result)`$.get("Productset.jsp").done(function(result){datas=result});` – Quentin Roger May 30 '16 at 11:30
  • Is there any way other than using ajax? I need to fill the text box through auto complete by getting the data from database(Productset.jsp) using javascript – sound May 31 '16 at 10:50
  • You can set the source of the autocomplete like tin this exemple : https://jqueryui.com/autocomplete/#remote, so for you it ll be `$(".auto").autocomplete({ source: "Productset.jsp" });` So in my fiddle replace my datas var by "Productset.jsp". – Quentin Roger May 31 '16 at 11:00
  • When I tried like this `jQuery(function(){ $("#product").autocomplete("Productset.jsp"); }); ` the first text box alone is getting filled through auto complete but when i changed the code to this `jQuery(function(){ $("#button").click(function(e) { addRow(); $(".auto").autocomplete({ source: "Productset.jsp" }); });` nothing is happening ,autocomplete is not even reflecting in the first text box – sound May 31 '16 at 11:42
  • So you must do an ajax call to productset.jsp :) – Quentin Roger May 31 '16 at 11:43
  • Can you please help me in changing my code by using ajax ? – sound May 31 '16 at 11:50
  • I edited my answer, but I think you should return json from from your jsp page to not have to parse a text file in js. Have a good day. – Quentin Roger May 31 '16 at 12:23
0

In my code the dynamically created text box doesn't take the jquery auto complete function.So including the auto complete function inside the addrow() method will fill the dynamically created text boxes with the auto complete data.

The id selector will only fill the first text box with the auto complete data.So use this $('input[name="product"]').auto complete("Productset.jsp"); in the jquery function to fill all the text boxes.

This is the complete code.

<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>
sound
  • 55
  • 2
  • 11