96

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

Andrew
  • 18,680
  • 13
  • 103
  • 118
Ben
  • 16,275
  • 9
  • 45
  • 63
  • 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 http://dev.jquery.com/ – cletus Apr 17 '10 at 22:40
  • 1
    What about the 'change' event? – ZippyV Apr 17 '10 at 22:42
  • @cletus Indeed, it is a Jquery 1.4.2 bug. 1.3.2 works just fine. – Ben Apr 17 '10 at 23:00
  • I'm seeing the same behavior in both 1.4.2 and 1.3.2: http://jsfiddle.net/HCUNn/ – Nick Craver Apr 17 '10 at 23:02
  • @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. – Ben Apr 17 '10 at 23:23

13 Answers13

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

tcurdt
  • 14,518
  • 10
  • 57
  • 72
  • 1
    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'. – Ben Apr 17 '10 at 23:09
  • @Ben - You have to trigger it in a different way to get this to run, see my answer for the trigger statement. – Nick Craver Apr 17 '10 at 23:13
  • @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. – Ben Apr 17 '10 at 23:27
  • 19
    and for newer versions of jquery the function is prop("checked") instead of attr("checked") in case that catches anyone else out. – danski Sep 13 '13 at 00:55
  • I would avoid 'prop' due to non-backwards-compatibility, esp. in IE. – vapcguy Jan 24 '15 at 02:04
  • 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. – atomless Jun 13 '16 at 08:42
  • 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. – Robb Sadler Sep 29 '17 at 16:48
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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
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');
  }
});
atomless
  • 1,272
  • 15
  • 18
  • 2
    `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. – dhaupin Aug 21 '17 at 19:18
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"));
    });
});
Srđan Stanić
  • 740
  • 1
  • 8
  • 17
  • 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.... – vapcguy Jan 24 '15 at 02:08
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.

ChillyPenguin
  • 1,150
  • 12
  • 18
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");
}
});
Tejas Soni
  • 551
  • 3
  • 10
2
$("#personal").click(function() {
      if ($(this).is(":checked")) {
            alert('Personal');
        /* var validator = $("#register_france").validate(); 
        validator.resetForm(); */
      }
            }
            );

JSFIDDLE

Surya R Praveen
  • 3,393
  • 1
  • 24
  • 25
1
  $("#checkbox").change(function(e) {

  if ($(this).prop('checked')){
    console.log('checked');
  }
});
Superman
  • 39
  • 2
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.

Yuri Ghensev
  • 2,507
  • 4
  • 28
  • 45
0
$( "#checkbox" ).change(function() {
    if($(this).is(":checked")){
        alert('hi');
    }

});
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.

RussellUresti
  • 6,211
  • 4
  • 28
  • 26
-1

Most fastest and easy way:

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

$el[0].checked;

$el - is jquery element of selection.

Enjoy!

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
-2
if ($.browser.msie) {
    $("#myCheckbox").click(function() { $(this).trigger('change'); });
}

$("#myCheckbox").change(function() {
        alert($(this).is(":checked"));
    });
Sten Muchow
  • 6,623
  • 4
  • 36
  • 46