tags:

views:

195

answers:

4

I have a method that I want to take some action depending on the 'checked' status of a checkbox. The 'click' event works as expected, but the 'myFunction' call in the foreach loop does not:

$(document).ready(function(){
  $('#TreeView1 :checkbox')
    .click(HandleCheckbox); // Works fine

  // Go through the entire Category treeview to 
  // see if there are any checkboxes that are already
  // checked.
  $.fn.myFunction = HandleCheckbox;
  $(":checked:checkbox").each(function(index) {
    // In the HandleCheckbox 'this' is undefined.
    $(this).myFunction(); 
  });

});

function HandleCheckbox() {
  alert(this.name + '=' + this.checked);
}

In the above code, when the '.click' method fires, 'this' is defined, as expected. When I call 'muFunction' in the foreach loop, 'this' is undefined in the 'HandleCheckbox' function.

I am still learning the jQuery ropes, so if there is a 'better' or easier way of doing this, please let me know.

Thanks.

A: 

Try this:

$("input:checkbox:checked").each(function(index) {
    $(this).myFunction.apply(this); 
  });
Artem Barger
+2  A: 

In javascript, this refers to the owner of the object. For an event, this is the object that fired the event. However, the attribute isn't inherited for called functions from said function/event handler. While one might think it should work in the example you gave, I'm not fully knowledgeable about the intricacies of the language, but I think this is the culprit here. Pass along a reference to this if you would like to use it, like so:

$(this).myFunction(this);

This reminds me, you can get around this by using:

// this becomes the `this` "keyword" without defining a parameter to hold it
$(this).myFunction.apply(this);
Cide
Personally I prefer this since it doesn't require one time use variables be defined that look useless.
Spencer Ruport
+1  A: 

A generic way to solve this scope problem:

parent_func = this;
$(":checked:checkbox").each(function(index) {
  $(parent_func).myFunction(); 
});
Brian Ramsay
+5  A: 

This would also work:

$(":checked:checkbox").each(HandleCheckbox)
bytebrite
This was the most elegant solution for my situation. Thanks.
Tod1d