简体   繁体   中英

Jquery autocomplete on dynamically created inputs

I am still learning javascript and Jquery . I am creating simple autocomplete with jQuery:

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

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.

Thanks for any help.

Have a nice day!

As a ID is unique you should not assign a ID twice. Use a class for this instead. So your code would look something like this:

JS:

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

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

HTML:

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

Hope this helps

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