0

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!

Rahul Gupta
  • 9,775
  • 7
  • 56
  • 69
Mario
  • 187
  • 2
  • 10
  • Possible duplicate of [How can I add jquery ui autocomplete to a dynamically created element?](https://stackoverflow.com/questions/6670918/how-can-i-add-jquery-ui-autocomplete-to-a-dynamically-created-element) – Rahul Gupta Dec 26 '17 at 07:34

1 Answers1

0

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

  • Hello, it is the same, as with ID. Because every new element creates dynamically and Jquery autocomplete do not know about them. Autocomplete knows only about static content generates when page loads. I need to check it everytime when new element with that class, or id appears. – Mario Dec 05 '17 at 23:49