Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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;
    });
});

Post a Comment for "Jquery: Use Autocomplete() On Input Elements Added To Page After Dom Was Loaded"