将自动完成应用于包含数据库中数据的动态生成的文本框


Apply autocomplete to dynamically generated textboxes with data from database

关于我的查询,我已经在stackoverflow上经历了许多问题,但无法将它们应用于我的问题。

因此,我在这里提供我一直在使用的文件。

我成功地将自动完成与静态文本框一起使用。我从数据库中获取数据。但是,我无法弄清楚如何为动态生成的文本框执行此操作。我希望为包含数据库中数据的动态生成的文本框实现自动完成功能

这是我的文件:

索引.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>

自动完成.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";
    }
}

?>

只需在新

添加的输入添加到 DOM 后对新添加的输入调用 .autocomplete() 函数

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

我建议你将用于自动完成的初始化代码($('#id'(.autocomplete(放在动态更新页面的js代码部分。我猜你正在使用ajax,所以你应该有类似的东西

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