views:

65

answers:

2

Hello!

I'm trying to pass an object into a function but think there's a problem with $(this) not actually being valid at the point of passing it in.

$('textarea[name*=quote]').live('bind',function(){

}).limit('10',$(this).parents('form').children().find('span[name*=qc]') );

The second parameter can be either a string or an object like $('span#qc'), but I also want to be able to pass in an object which references the current one.

Why? Because I have several forms on same page, each containing textarea#quote, so depending on which form is selected I want to be able to reference a particular element within the same form.

Anyone??

+1  A: 

You need to make a separate call for each individual instance using .each, like this:

$('textarea#quote').each(function() {
    $(this).live('bind',function(){

    }).limit('10',$(this).parents('form').children().find('span#qc') );
});
SLaks
Thanks SLaks, will that live update any new textarea#quote fields added to the dom via ajax etc even though it's inside the .each ?
regan
@regan - It will not, [`.live()`](http://api.jquery.com/live/) is an event handler, it cannot run a plugin on new elements...unless it's executed via an event `.live()` can listen for, which is not usually what you're after.
Nick Craver
+1  A: 

To bind all of them with access to $(this), use .each(), like this:

$('textarea[name*=quote]').each(function() {
   $(this).limit('10',$(this).closest('form').find('span[name*=qc]'));
});

If you want .live()-like functionality on the second part, you need to either use .livequery(), like this:

$('textarea[name*=quote]').livequery(function() {
   $(this).limit('10',$(this).closest('form').find('span[name*=qc]'));
});

Or alternatively, bind them like the first example and also bind when loading new elements, e.g. if you're using $.ajax(), it would look like this:

$.ajax({
  url: blah.html
  success: function(data) {
    //do something with data
    $('textarea[name*=quote]', data).each(function() {
     $(this).limit('10',$(this).closest('form').find('span[name*=qc]'));
   });
  }
});

The key here is , data, it provides a context to search in, so this is only executing on elements found in the returned data. You can also wrap this in a function to prevent duplication of code, like this:

function bindStuff(context) {
  $('textarea[name*=quote]', context || document).each(function() {
    $(this).limit('10',$(this).closest('form').find('span[name*=qc]'));
  });
}

In document.ready, call bindStuff(document), in $.ajax, you'd call bindStuff(data).

Nick Craver