6

I've got an <input type="checkbox" id="check1" />. How to catch change event for this checkbox if it was changed from script i.e. $('#check1').attr('checked', 'checked');?

Thanks.

3 Answers 3

5

Javascript doesn't fire events based on programmatic changes to form elements - to prevent infinite loops of events - so you have two (less-than-ideal) options:

  • Write a wrapper function which changes the attribute and calls your callback, and then force yourself to always use your wrapper function
  • Just call the callback yourself when you change the attribute
Sign up to request clarification or add additional context in comments.

1 Comment

If you changed the checkbox progammatically, then you can trigger the change event yourself. E.g., $("#myCheckbox").prop("checked", true).trigger("change").
1

I am not sure whether you are expecting this

1 Comment

Not really. I'm expecting that execution of code $('#check1').attr('checked', 'checked'); will fire change() event for that checkbox.
-1

This might be what you were looking for.

$(document).ready(function(){          
   $('#check1').click(function(){
      var n = $("#check1:checked").length;  
      alert(n);
   });
});

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.