patternjavascriptCritical
jQuery checkbox checked state changed event
Viewed 0 times
eventjquerystatecheckedcheckboxchanged
Problem
I want an event to fire client side when a checkbox is checked / unchecked:
Basically I want it to happen for every checkbox on the page. Is this method of firing on the click and checking the state ok?
I'm thinking there must be a cleaner jQuery way. Anyone know a solution?
$('.checkbox').click(function() {
if ($(this).is(':checked')) {
// Do stuff
}
});Basically I want it to happen for every checkbox on the page. Is this method of firing on the click and checking the state ok?
I'm thinking there must be a cleaner jQuery way. Anyone know a solution?
Solution
Bind to the
The main benefit of binding to the
Also note that I've used
Edit (see comments)
To get all checkboxes you have a couple of options. You can use the
Or you could use an attribute equals selector:
change event instead of click. However, you will probably still need to check whether or not the checkbox is checked:$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
}
});The main benefit of binding to the
change event over the click event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change event. Redacted in commentsAlso note that I've used
this.checked instead of wrapping the element in a jQuery object and using jQuery methods, simply because it's shorter and faster to access the property of the DOM element directly.Edit (see comments)
To get all checkboxes you have a couple of options. You can use the
:checkbox pseudo-selector:$(":checkbox")Or you could use an attribute equals selector:
$("input[type='checkbox']")Code Snippets
$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
}
});$(":checkbox")$("input[type='checkbox']")Context
Stack Overflow Q#8423217, score: 1447
Revisions (0)
No revisions yet.