Checking if checkbox is checked using jQuery. Various methods and issues
This article shows different methods on checking, if checkbox is check or set of checkboxes are set. jQuery is used. It also discussed some additional issues about this topic.
Checking, if checkbox is checked or not is quite easy with jQuery:
$('#checkbox-id').attr('checked');
However, not everyone is familiar with second approach to solve the very same problem:
$('#checkbox-id').is(':checked');
And for iterating through all checkboxes checked on current page (or other set of elements) you can use:
$("input[type=checkbox][checked]").each(function()
{
//Code goes here...
});
Note, that when you’re checking checkbox state in it’s own onChange
event, you’ll get an incorrect result!
This is a very specific situation, caused by a fact that onChange
event for checkboxes is fired in the middle of process of changing checkbox’s state. I.e. actual marking or unmarking of checkbox happens after onChange
has been fired.
Thus, inside onChange
event for checkbox which state you’re checking, you have to negate value you got to get real (actual) state:
onCheckboxChangeHandler: function(e)
{
var checked = !lokale.elements.$checkbox.is(":checked");
console.log(checked);
}
In every other situation (checking checkbox’s state outside it’s onChange
event) will always give you correct state and you don’t have to negate anything.
Another thing worth remembering is that Javascript cancels (not fires) onChange
event, if it would be fired as an effect of things done in another onChange
event for the same object. In other words: you can easily change checkbox’s state inside it’s on onChange event (for example to prevent checking or unchecking it in certain situations) without worry of creating endless loop.
This was a quite big problem in other languages (for example: Delphi). Where such action would create an endless chain of onChange
event calling itself.
This post is a slightly modified version of jQuery: Test/check if checkbox is checked article.