简体   繁体   中英

Apply autocomplete to dynamically generated textboxes with data from database

I have gone through many ques here on stackoverflow with regard to my query here but could not apply them to my problem.

Hence I am giving here my files that I have been using.

I am successfully able to use autocomplete with a static textbox. I get the data from the database. But however I am not able to figure out how to do it for dynamically generated textboxes. I want autocomplete feature to be implemented for dynamically generated textboxes with data from databases

here are my files:

index.php

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Auto Complete Input box</title>
   <link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
  <script type="text/javascript" src="jquery.js"></script>
   <script type="text/javascript" src="jquery.autocomplete.js"></script>
    <script>
     $(document).ready(function(){
    $("#name").autocomplete("autocomplete.php", {
    selectFirst: true
});
 });
 </script>

  <script>
   function addForm(){
  $("#forms").append(
    "<form><input type ='text' name='winner' id='winner'><br/></form>"
   );
 }
  </script>
 </head>

  <body>
  <label>Name:</label>
   <input name="name" type="text" id="name" size="20"/>
   <input type="button" name="addmore" id="addmore" value="Add More Winners" onclick="addForm();"/>
<div id = "dyanamic"></div>
 </body>
 </html>

autocomplete.php

  <?php
require 'config.php';
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
//$mysqli=mysql_connect('localhost','root','','emp_db') or die("Database Error");
$sql="SELECT name FROM employee WHERE name LIKE '%$my_data%' ORDER BY name";
$result = mysql_query($sql) or die(mysqli_error());

if($result)
{
    while($row=mysql_fetch_array($result))
    {
        echo $row['name']."\n";
    }
}

?>

Just call your .autocomplete() function on your newly added inputs AFTER they have been added to the DOM

function addForm() {
    $("#forms").append("<form><input type ='text' name='winner' id='winner'><br/></form>");
    $("#winner").autocomplete("autocomplete.php", {
        selectFirst: true
    });
}

I suggest you put the init code ($('#id').autocomplete) for autocompletion on the js code part that update your page dynamically. I guess you're using ajax, so you should have someting like that

$.ajax({
    // your ajax options here
}).done(
    // here you update your html page
    // and then set the autocomplete on the new element
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM