Enabling jQuery autocomplete for dynamically generated input fields

I read almost every article I could find on how to do this, but I still fail. mainly because I'm a fan of jQuery / Javascript.

I have a website containing one input element. I managed to get jQuery Autocomplete working perfectly on this. The problem is that when I dynamically add additional elements using the .append method, these new elements do not work with autocomplete.

See jsfiddle: http://jsfiddle.net/aktive/r08m8vvy/

see jsfiddle for full code sample 

Thank you in advance for your help! :) -Dean

+1
javascript jquery autocomplete
Oct 22 '14 at 0:33
source share
4 answers

You must bind autocomplete after adding new elements

 $(wrapper).find('input[type=text]:last').autocomplete({ source: availableAttributes }); 

See an example: http://jsfiddle.net/r08m8vvy/4/

+3
Oct 22 '14 at 0:43
source share

See http://jsfiddle.net/r08m8vvy/2/

Enter a new ID entry and call auto-complete. The selected initial autocompate call does not include dynamically added inputs.

  $(wrapper).append('<div><input id="' + x + '" type="text" name="mytext"/><a href="#" class="remove_field">Remove</a></div>'); //add input box $( "input[id="+ x +"]" ).autocomplete({ source: availableAttributes }); 
+3
Oct 22 '14 at 0:41
source share

I updated the fiddle http://jsfiddle.net/r08m8vvy/5/

You need to bind autocomplete for a new item

 $(wrapper).append($('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>').find(":text").autocomplete({ source: availableAttributes })); 
+2
Oct 22 '14 at 0:43
source share

I really found that a more reliable way was to bind the focus action with 'on' to trigger automatic completion depending on the class of the field and destroy it when exiting. Thus, it cleans garbage and only in it when you need it.

I used it with line cloning and even did deep cloning that would clone the plus and minus buttons for strings, this is not autocomplete cloning.

 var auto_opts = {...opts...} $('body').on('focus', '.search_field', function(){ $(this).autocomplete(auto_opts).on('blur', function(){$(this).autocomplete('destroy')}); }); 

It also means that you are not forced to use the last line, because it works in the field when you focus on it.

0
Oct 21 '16 at 1:59
source share



All Articles