jQuery, checkboxes and .is(":checked")
$('#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.
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.
As of June 2016 (using jquery 2.1.4) none of the other suggested solutions work. Checking attr('checked')
always returns undefined
and is('checked)
always returns false
.
Just use the prop method:
$("#checkbox").change(function(e) {
if ($(this).prop('checked')){
console.log('checked');
}
});
I'm still experiencing this behavior with jQuery 1.7.2. A simple workaround is to defer the execution of the click handler with setTimeout and let the browser do its magic in the meantime:
$("#myCheckbox").click( function() {
var that = this;
setTimeout(function(){
alert($(that).is(":checked"));
});
});