jQuery, checkboxes and .is(":checked")
Asked Answered
F

13

98

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');

Fourthclass answered 17/4, 2010 at 22:33 Comment(5)
I've just verified this. You are completely correct. That does seem like it might be a bug. I'd raise it as a bug with jQuery and see what happens dev.jquery.comDionysiac
What about the 'change' event?Junejuneau
@Dionysiac Indeed, it is a Jquery 1.4.2 bug. 1.3.2 works just fine.Fourthclass
I'm seeing the same behavior in both 1.4.2 and 1.3.2: jsfiddle.net/HCUNnMarjoriemarjory
@Nick It still does the opposite of what a normal mouse click would do. I honestly don't know why 1.3.2 works for me and 1.4.2 doesn't, but still, that needs to be changed.Fourthclass
T
112
$('#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.

Tumefy answered 17/4, 2010 at 22:56 Comment(7)
I've tried that, "$(#myCheckbox).click()" unchecks/checks the box but the change function is never triggered. I've also tried changing the 'checked' attribute instead of calling click() and even setting the 'change' function to 'live'.Fourthclass
@Fourthclass - You have to trigger it in a different way to get this to run, see my answer for the trigger statement.Marjoriemarjory
@Nick Thanks, I will accept tcurdt answer as he was the first to come out with the solution. Silly me i didn't triggered the 'change' method.Fourthclass
and for newer versions of jquery the function is prop("checked") instead of attr("checked") in case that catches anyone else out.Azaleah
I would avoid 'prop' due to non-backwards-compatibility, esp. in IE.Corneous
This no longer works. Binding to the change event is right but attr('checked') returns undefined regardless of the checked state of the checkbox input.Caesium
per @danski's comment, you need to use prop() for newer jQuery. I don't believe this is a backward compatibility issue, as you specify which version of jquery you wish to use on your site.Ingratiate
M
27

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.

Marjoriemarjory answered 17/4, 2010 at 23:6 Comment(0)
C
10

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');
  }
});
Caesium answered 13/6, 2016 at 9:5 Comment(1)
is('checked) will return false because "checked" is not a CSS pseudo selector. The correct one should be is(':checked') so it looks for ":checked" instead.Anuran
B
4

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"));
    });
});
Boride answered 5/9, 2012 at 10:31 Comment(1)
Yep! A little offtopic, but I had to do the same in Kendo grids with checkboxes when someone clicked "Add new record" if I wanted it to be "Active" by default. I had to also give it a time of 500ms. Then I had to add .click(), then set .attr('value', 'true'), then .change(), then .blur() before it would programmatically set the box when I clicked the "Update" button programmatically....Corneous
S
3
$("#personal").click(function() {
      if ($(this).is(":checked")) {
            alert('Personal');
        /* var validator = $("#register_france").validate(); 
        validator.resetForm(); */
      }
            }
            );

JSFIDDLE

Slifka answered 23/1, 2019 at 13:27 Comment(0)
R
2

If you anticipate this rather unwanted behaviour, then one away around it would be to pass an extra parameter from the jQuery.trigger() to the checkbox's click handler. This extra parameter is to notify the click handler that click has been triggered programmatically, rather than by the user directly clicking on the checkbox itself. The checkbox's click handler can then invert the reported check status.

So here's how I'd trigger the click event on a checkbox with the ID "myCheckBox". Note that I'm also passing an object parameter with an single member, nonUI, which is set to true:

$("#myCheckbox").trigger('click', {nonUI : true})

And here's how I handle that in the checkbox's click event handler. The handler function checks for the presence of the nonUI object as its second parameter. (The first parameter is always the event itself.) If the parameter is present and set to true then I invert the reported .checked status. If no such parameter is passed in - which there won't be if the user simply clicked on the checkbox in the UI - then I report the actual .checked status:

$("#myCheckbox").click(function(e, parameters) {
   var nonUI = false;
        try {
            nonUI = parameters.nonUI;
        } catch (e) {}
        var checked = nonUI ? !this.checked : this.checked;
        alert('Checked = ' + checked);
    });

JSFiddle version at http://jsfiddle.net/BrownieBoy/h5mDZ/

I've tested with Chrome, Firefox and IE 8.

Ruthi answered 21/6, 2012 at 5:41 Comment(0)
F
2
<input id="widget-wpb_widget-3-custom_date" class="mycheck" type="checkbox" value="d/M/y" name="widget-wpb_widget[3][custom_date]" unchecked="true">    

var atrib = $('.mycheck').attr("unchecked",true);
$('.mycheck').click(function(){
if ($(this).is(":checked")) 
{
$('.mycheck').attr("unchecked",false);
   alert("checkbox checked");
}
else
{
$('.mycheck').attr("unchecked",true);
 alert("checkbox unchecked");
}
});
Ferrotype answered 21/8, 2015 at 12:50 Comment(1)
Some comments would be niceStage
L
1
  $("#checkbox").change(function(e) {

  if ($(this).prop('checked')){
    console.log('checked');
  }
});
Lentamente answered 28/2, 2017 at 10:52 Comment(0)
C
0

Well, to match the first scenario, this is something I've come up with.

http://jsbin.com/uwupa/edit

Essentially, instead of binding the "click" event, you bind the "change" event with the alert.

Then, when you trigger the event, first you trigger click, then trigger change.

Cochard answered 17/4, 2010 at 23:4 Comment(0)
U
0

In addition to Nick Craver's answer, for this to work properly on IE 8 you need to add a additional click handler to the checkbox:

// needed for IE 8 compatibility
if ($.browser.msie)
    $("#myCheckbox").click(function() { $(this).trigger('change'); });

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

//Trigger by:
$("#myCheckbox").trigger('click').trigger('change');

Otherwise the callback will only be triggered when the checkbox loses focus, as IE 8 keeps focus on checkboxes and radios when they are clicked.

Haven't tested on IE 9 though.

Umbilical answered 4/6, 2012 at 16:30 Comment(0)
C
0
$( "#checkbox" ).change(function() {
    if($(this).is(":checked")){
        alert('hi');
    }

});
Custard answered 1/7, 2014 at 9:28 Comment(2)
Kindly mention some detailsCamass
Seems like this is just a repeated answer, using change instead of the OP's click, and just uses an if statement as a different way of testing for :checked.Corneous
N
-1

Most fastest and easy way:

$('#myCheckbox').change(function(){
    alert(this.checked);
});

$el[0].checked;

$el - is jquery element of selection.

Enjoy!

Numerable answered 20/5, 2014 at 11:2 Comment(0)
C
-2
if ($.browser.msie) {
    $("#myCheckbox").click(function() { $(this).trigger('change'); });
}

$("#myCheckbox").change(function() {
        alert($(this).is(":checked"));
    });
Casta answered 27/1, 2014 at 8:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.