Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery checkbox checked state changed event

I want an event to fire client side when a checkbox is checked / unchecked:

$('.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?

like image 521
AnonyMouse Avatar asked Dec 07 '11 22:12

AnonyMouse


People also ask

How do I check if a checkbox is checked in an event?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

Do something when checkbox is checked jQuery?

prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.

How can create checkbox click event in jQuery?

change() updates the textbox value with the checkbox status. I use . click() to confirm the action on uncheck. If the user selects cancel, the checkmark is restored but .


1 Answers

Bind to the 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 comments

Also 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']") 
like image 144
James Allardice Avatar answered Sep 27 '22 19:09

James Allardice