Using jQuery.live() on each element of the caller object of a plugin

I’ve built a filter plugin in jQuery that pops up an unordered list of query results from a database after I click an input textfield and filters the list depending on the changing content of the input field. I guess it’s clear so far, we see many such things.

After spending some time with building it into a plugin I quickly realised that the .live() function I use on the list items instead of .click() (I have to use it as the list items are generated dynamically) doesn’t work the way I want it to work. After some googling, I found some relating articles, but my real problem is that the .live() function binds my click event to all the input fields with which I use the plugin, and after I click a list item it pushes the text in all of the callers.

Here’s a snapshot of the problem.

Here’s the relevant code:

I call the plugin like this on two input fields:

$  ('#inputf').lookupFilter({ dataSource: '/GetTownsForCounty/1', loadOnce: true });
$  ('#inputfield').lookupFilter({ dataSource: '/GetTownsForCounty/1', loadOnce: true });

And defined the plugin like this:

(function( $   ){
    var settings = {
         datarows: '#datarows',
         //  other settings here
    };
    $  .fn.lookupFilter = function( options ) {
      return this.each(function() {
        var $  this = $  (this);
        if( options ) {
            $  .extend( settings, options );
        }

     //  Generating & filtering the list items here

        $  this.keyup( function(){
            if($  (this).val() != '') {
                $  ("#datarows > li:not([name^='" + $  (this).val().toLowerCase() + "']):visible").hide();
                $  ("#datarows > li[name^='" + $  (this).val().toLowerCase() + "']:hidden").show();
            }
        })
        .keyup();  

        ajaxRequest(settings.dataSource);

        $  (settings.datarows + ' > li').live('click', function() {
            pushText($  this, $  (this).text());
            alert('right after pushText for id: ' + $  this.attr('id'));
        });
     });
})(jQuery);

I tried the above mentioned source’s solution like this (changing the $ (settings.datarows… line to this):

$  (settings.datarows + ' > li').liveBindTest();

And introducing the function itself:

$  .fn.liveBindTest = function () {
      $  (this.selector).live('click', function() {
          console.log('live clicked ' + $  (this).attr('id'));
          return false;
      });

But it returns both input fields’ ID again.

So, question is whether there is a workaround to bind only the relevant input field to the click event, or is it me who do things wrong? (Or is it an actual problem that no one has spotted yet?)

Thanks for the help.

newest questions tagged jquery – Stack Overflow

About Admin