Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, checkboxes and .is(":checked")

When I bind a function to a checkbox element like:

$("#myCheckbox").click( function() {     alert($(this).is(":checked")); }); 

The checkbox changes its checked attribute before the event is triggered, this is the normal behavior, and gives an inverse result.

However, when I do:

$("#myCheckbox").click(); 

The checkbox changes it checked attribute after the event is triggered.

My question is, is there a way to trigger the click event from jQuery like a normal click would do (first scenario)?

PS: I've already tried with trigger('click');

like image 385
Ben Avatar asked Apr 17 '10 22:04

Ben


People also ask

How do you check if the checkbox is checked or not?

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.


2 Answers

$('#myCheckbox').change(function () {     if ($(this).prop("checked")) {         // checked         return;     }     // not checked }); 

Note: In older versions of jquery it was OK to use attr. Now it's suggested to use prop to read the state.

like image 86
tcurdt Avatar answered Sep 21 '22 05:09

tcurdt


There is a work-around that works in jQuery 1.3.2 and 1.4.2:

$("#myCheckbox").change( function() {     alert($(this).is(":checked")); });  //Trigger by: $("#myCheckbox").trigger('click').trigger('change');​​​​​​​​​​​​​ 

But I agree, this behavior seems buggy compared to the native event.

like image 45
Nick Craver Avatar answered Sep 22 '22 05:09

Nick Craver