Phil
Phil

Reputation: 182

Jquery: use autocomplete() on input elements added to page after DOM was loaded

I am using this autocomplete Plugin working with Jquery: jQuery Autocomplete Mod

You use it by simple adding $("selector").autocomplete(url [, options]);

There are 5 Input elements (id = channel followed by a number) when the page load that's why I use this code to init the autocomplete plugin on each input:

$(document).ready(function() {
      $('input[id^="channel"]').each(function(){       
        $(this).autocomplete(
          "autocomplete/autocomplete.php",
          {
                some options that don't matter now I guess
          }
        );        
  });
});

But now I also want the autocomplete plugin to work on Input elements (same id syntax) that are added by calling a javascript function (by clicking on a link) after the page is loaded.

I now there is the live() function of Jquery but I just don't know how I should use it here.

I am sure there is a nice and easy way to do it but I just can#t think of the right way at the moment.

Thanks in advance!

Phil

Upvotes: 2

Views: 3024

Answers (1)

tvanfosson
tvanfosson

Reputation: 532435

Because autocomplete adds the events handlers, there isn't really any good way to get it to work with dynamically added elements. You'd have to modify the plugin so that it would know, perhaps optionally, to apply the handlers dynamically. That's a fair amount of work. An easier way is to abstract the handler into a function, then apply it to the original elements and each new element after it is added, perhaps in a callback.

$(document).ready(function() {
    var nextChannel = $('input[id^="channel"]').length + 1;
    function addAutocomplete( selector) {
        $(selector).each(function(){       
           $(this).autocomplete(
              "autocomplete/autocomplete.php",
              {
                    some options that do not matter now I guess
           });        
        });
    });
    addAutocomplete('input[id^="channel"]');

    $('.addSearch').click( function() {
         var input = $('<input id="channel' + nextChannel + '" type="text" />')
                        .appendTo('form');
         addAutocomplete( input );
         ++nextChannel;
         return false;
    });
});

Upvotes: 2

Related Questions