12

How can I check if a checkbox is checked via jQuery?

Can I just add an ID or class to the element and do this?

if($('#element').val() == 1) { 
  //do stuff 
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
user2888263
  • 243
  • 1
  • 3
  • 7

3 Answers3

5
if($('#element').is(':checked')){

    //checkbox is checked

}

or

if($('#element:checked').length > 0){

    //checkbox is checked

}

or in jQuery 1.6+:

if($('#element:checked').prop('checked') === true){

    //checkbox is checked

}
Ben Wong
  • 1,987
  • 2
  • 19
  • 20
4

It depends on where you are trying to do this. Generally you can do:

$('#element').is(':checked');

or

$('#element')[0].checked;

or

 $('#element').prop('checked'); 

or older version of jquery ( < 1.6) that doesn't support prop, attr used to do the job of prop as well to set/reset properties of element (Incase of standalone attributes like checked, selected, disabled etc...);

 $('#element').attr('checked') //will return boolean value

If it is in the context of the checkbox like, if in a change event you can just do:

  this.checked
PSL
  • 123,204
  • 21
  • 253
  • 243
  • @user2864740 Not really see the comment and the statement before that. For your proof test it against older version of jquery <=1.5 or so – PSL Oct 19 '13 at 04:37
  • 1
    @user2864740 Sorry, really sleepy. `:P` Either way, yeah, in jQuery < 1.6, there was no `.prop()` so `.attr()` did retrieve DOM properties back then. – Fabrício Matté Oct 19 '13 at 04:38
  • Also older version of jq that doesn't support prop used to make up for setting property for standalone attributes. – PSL Oct 19 '13 at 04:38
  • @user2864740 Here you go one with version 1.5 http://jsfiddle.net/tgY2Y/ – PSL Oct 19 '13 at 04:41
0

Using element's id or class is a good way of doing all this, but since we're using jQuery, you might use their API and here is the solution:

$('input[type="checkbox"]').is(':checked') {
  // do the stuff here..
}

You can also use #element instead of the input[type="checkbox"]'.

This way, you can get to know that the checkbox is checked.

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103