简体   繁体   English

jQuery自动完成动态创建的输入

[英]Jquery autocomplete on dynamically created inputs

I am still learning javascript and Jquery . 我还在学习javascriptJquery I am creating simple autocomplete with jQuery: 我正在使用jQuery创建简单的autocomplete功能:

 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script> $(function() { $( "#nazov" ).autocomplete({ minLength: 2, source: 'private/search.php', select: function(event, ui) { document.getElementById("pocet").value = ui.item.pocet; } }); }); 
  <label for="nazov">Názov: </label> <input id="nazov"> <input id="pocet"> 

I have some basic JS function to create inputs. 我有一些基本的JS函数来创建输入。 Every new input has id="nazov" But autocomplete works only with non-dynamic inputs and every new input that is dynamically created do not work. 每个新输入都具有id="nazov"但是自动完成功能仅适用于非动态输入,并且动态创建的每个新输入均不起作用。

I think it is because autocomplete function do not know about new input. 我认为这是因为自动完成功能不了解新输入。 It is any way to change autocomple to looking for new inputs and autocomplete each one with different return? 有什么方法可以将自动补全更改为寻找新的输入,并自动完成具有不同收益的每个输入? I found some deprecated function .live() and .on() but I think I cannot use it here, or I do not know how. 我找到了一些不赞成使用的函数.live().on()但我想我不能在这里使用它,或者我不知道如何使用。

Thanks for any help. 谢谢你的帮助。

Have a nice day! 祝你今天愉快!

As a ID is unique you should not assign a ID twice. 由于ID是唯一的,因此您不应两次分配ID。 Use a class for this instead. 为此,请使用类。 So your code would look something like this: 因此,您的代码将如下所示:

JS: JS:

$(function() {
    $(".nazov").autocomplete({
    minLength: 2,
    source: 'private/search.php',

    select: function(event, ui) {
        document.getElementByClass("pocet").value = ui.item.pocet;
    }
  });
});

HTML: HTML:

<label for="nazov">Názov: </label>
<input class="nazov">
<input class="pocet">

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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