0

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.

4 Answers 4

6

This would also work:

$(":checked:checkbox").each(HandleCheckbox)
Sign up to request clarification or add additional context in comments.

1 Comment

This was the most elegant solution for my situation. Thanks.
3

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

1 Comment

Personally I prefer this since it doesn't require one time use variables be defined that look useless.
1

A generic way to solve this scope problem:

parent_func = this;
$(":checked:checkbox").each(function(index) {
  $(parent_func).myFunction(); 
});

Comments

0

Try this:

$("input:checkbox:checked").each(function(index) {
    $(this).myFunction.apply(this); 
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.