42

I'm using Jquery's toggle event to do some stuff when a user clicks a checkbox, like this:

$('input#myId').toggle(
function(){
//do stuff  
},
function(){
//do other stuff    
}
);

The problem is that the checkbox isn't being ticked when I click on the checkbox. (All the stuff I've put into the toggle event is working properly.)

I've tried the following:

$('input#myId').attr('checked', 'checked');

and

$(this).attr('checked', 'checked');

and even simply

return true;

But nothing is working. Can anyone tell me where I'm going wrong?

Edit - thanks to all who replied. Dreas' answer very nearly worked for me, except for the part that checked the attribute. This works perfectly (although it's a bit hacky)

$('input#myInput').change(function ()
{
    if(!$(this).hasClass("checked"))
    {
        //do stuff if the checkbox isn't checked
        $(this).addClass("checked");
        return;
    }

    //do stuff if the checkbox isn't checked
    $(this).removeClass('checked');
});

Thanks again to all who replied.

3
  • It's physically not showing in the browser as being checked when you click on it, or merely your event isn't firing?
    – J Cooper
    Commented Dec 10, 2008 at 10:42
  • The event is firing correctly and all the correct code is executing, but the checkbox just isn't getting checked! If I post the values from the form, the checkbox value isn't being posted through either. Commented Dec 10, 2008 at 10:48
  • 1
    Instead of using addClass, hasClass, and removeClass use toggleClass. Commented Apr 13, 2010 at 6:33

10 Answers 10

52

Use the change event instead of the toggle event, like such:

$('input#myId').change(function () {
    if ($(this).attr("checked")) {
        //do the stuff that you would do when 'checked'

        return;
    }
    //Here do the stuff you want to do when 'unchecked'
});
7
  • Thanks for your input, but I had to add and remove classes rather than check attributes - for some reason I couldn't quite get that working. I'll post the full solution (at least what worked for me) above. Thanks again! Commented Dec 10, 2008 at 12:19
  • I've always wondered the practical difference between == and ===...what about this compare makes === necessary? Commented Dec 10, 2008 at 14:33
  • 1
    the '==' performs type coercion (conversion), meaning the compiler will implicitly try to convert the values. For example, [1 == true //true] because it converts the 'true' to a 1...but [1 === true //false] because a number is not equal to a boolean Commented Dec 10, 2008 at 19:54
  • 9
    instead of $(this).attr("checked") you can simply call this.checked and it will return checked value
    – Sergey
    Commented Jan 25, 2010 at 2:42
  • 4
    if($(this).is(:checked)) // better way to check
    – kasp3r
    Commented Dec 2, 2010 at 9:05
18

While using the change event handler suggested by Dreas Grech is appropriate, it doesn't work well in IE 6 & 7, which doesn't fire the change event until the focus is blurred (that is, until you click outside the area of the checkbox). As QuirksMode say, "it's a serious bug".

You might want to use the click event handler, but that won't work with keyboard navigation. You need to register a keyup handler too...

See also this related question.

I haven't yet found a good cross-browser solution that supports both mouse clicks and keyboard activation of the checkboxes (and doesn't fire too many events).


Regarding your solution for checking whether the checkbox is checked or not, instead of adding your own checked class, you may use HTML's checked attribute:

$('input#myInput').change(function () {
    if ($(this).attr("checked")) {
        //do stuff if the checkbox is checked
    } else {
        //do stuff if the checkbox isn't checked
    }
});

Any browser sets the checked attribute of an input element to the value "checked" if the checkbox is checked, and sets it to null (or deletes the attribute) if the checkbox is not checked.

8

why not using $.is() ?

$('input#myId').change(
    function() {
        if ($(this).is(':checked')) {
            // do stuff here 
        } else {
            // do other stuff here
        }
});
0
2

This is an answer by MorningZ (I found it here) that makes totally sense:

The part you are missing is that "checkbox" is a jQuery object, not a checkbox DOM object

so:

checkbox.checked sure would error because there is no .checked property of a jQuery object

so:

checkbox[0].checked would work since the first item on a jQuery array is the DOM object itself.

So in your change() function you can use

$(this)[0].checked
0
1
$('input#myId').toggle(
  function(e){
    e.preventDefault();
    //do stuff      
    $(this).attr('checked', 'true');
  },
  function(e){
    e.preventDefault();
    //do other stuff        
    $(this).attr('checked', 'false');
  }
);
1

this worked for me............ check it

$(":checkbox").click(function(){
if($(this).attr("id").split("chk_all")[1])
 {
  var ty  = "sel"+$(this).attr("id").split("chk_all")[1]+"[]";
  if($(this).attr("checked"))
   {
    $('input[name="'+ty+'"]').attr("checked", "checked");
   }
  else
   {
    $('input[name="'+ty+'"]').removeAttr("checked");
   }
 }
})
0

I did a similar approach but simply using the checked attribute such as

 //toggles checkbox on/off
    $("input:checkbox").change(
        function(){
           if(!this.checked){
             this.checked=true;
           }
           else{
             this.checked=false;
           }
         }
       );
 //end toggle
0
    $("input[type=checkbox][checked=false]")// be shure to set to false on ready
    $("input#Checkbox1").change(function() {
        if ($(this).attr("checked")) {
            $("#chk1").html("you just selected me")//the lable
        } else {$("#chk1").html("you just un selected me") }    
    });
1
  • works for me and I use it to check before some logic is applied. Very handy to provide user feedback
    – philljohn
    Commented Dec 3, 2010 at 1:13
0

Try using a non-jquery function:

function chkboxToggle() {
  if ($('input#chkbox').attr('checked'))
    // do something
  else
    // do something else
}

then in your form:

<input id="chkbox" type="checkbox" onclick="chkboxToggle()" />
0

Try:

$(":checkbox").click(function(){
  if($(this).attr("checked"))
   {
    $('input[name="name[]"]').attr("checked", "checked");
   }
  else
   {
    $('input[name="name[]"]').removeAttr("checked");
   }
})

Not the answer you're looking for? Browse other questions tagged or ask your own question.