Search code examples
javascriptjquerysearchlive

Adding jQuery live search to dynamic inputs


I am using the jQuery live search plugin and need to bind it to all instances of a class. My class instances may or may not be dynamic.

I know I can accomplish binding it to the dynamic class instances by nesting it within a jQuery Live function, E.G $(".myLink").live(click function(){});

However, I also need the non dynamic classes to have the binding as well.

How can I accomplish this without defining my liveSearch binding twice? (Once at document ready for the static elements, and once in my click handler for the dynamic elements).

Here's my liveSearch code, not sure if it matters.

$(".myClass").liveSearch({
url: 'foo.php',
id: 'liveSearchID',
parent: '.myParent',
});

Thanks much.


Solution

  • You could use jQuery .on() to bind liveSearch to present (non dynamic) or future elements like :

    $("#parentContainer").on("click", ".myClass", function(){
      $(this).liveSearch({
         // options
      }); // liveSearch
    }); // on
    

    Notice that you have to apply .on() to the parent container of your selector .myClass and then pass the event, .myClass as descendant selector and the handler.

    See DEMO

    .on() requires jQuery 1.7+

    EDIT (Dec 15, 2012 - 4:13pm PT):

    Users of older versions of jQuery should use .delegate() in preference to .live() ... so just tweak your code this way .delegate(selector, eventType, handler) (still applying .delegate() to the parent container) like :

    $("#parentContainer").delegate(".myClass", "click", function() {
      $(this).liveSearch({
         // options
      }); // liveSearch
    }); // delegate
    

    See new DEMO using .delegate() (requires jQuery v1.4.2+)