1

Is there any better way to do this :

var IsC = $('input[type=checkbox]').attr("checked") == "checked" ? true : false;

?

3
  • You have to be more precise about what you want to test. Do you want to know where there is a checkbox that is checked or whether a specific one is checked? Your code will only test whether the first one is checked (which is ok as long as you don't have more than one). But apart from that I'm quite certain this has been asked before here... Commented Jul 11, 2012 at 11:02
  • 1
    possible duplicate of Jquery - Check if checkbox is checked
    – rlemon
    Commented Jul 11, 2012 at 11:03
  • Anyone with 1k rep or higher should be ashamed answering this... probably one of the most asked questions.. you are just rep farming
    – rlemon
    Commented Jul 11, 2012 at 11:04

4 Answers 4

4

You can use the :checked selector

var IsC = $('input[type=checkbox]').is(":checked");

Or :

var IsC = $('input[type=checkbox]:checked').length>0;
1
2
$("input[type=checkbox]").is(":checked")
1
var IsC = $('input[type=checkbox]').attr("checked") == "checked" ? true : false; 

is the same as just saying:

var IsC = $('input[type=checkbox]').attr("checked") == "checked";

since == will return true or false. (purely a javascript change)


The jQuery optimization (in terms of number of characters, at least) is:

var IsC = $('input:checkbox').is(':checked'); 
//returns true if at least one checkbox in the document is checked

You can add a scope for the comparison by telling the selector where the input should be found:

var IsC = $('#myForm input:checkbox').is(':checked');
0

One way is to use solution posted by dystroy.

Another is to use prop method instead of attr. Check examples at http://api.jquery.com/prop/

elem.checked
// true (Boolean) Will change with checkbox state

$(elem).prop("checked")
// true (Boolean) Will change with checkbox state

elem.getAttribute("checked")
// "checked" (String) Initial state of the checkbox; does not change

$(elem).attr("checked") //(1.6)
// "checked" (String) Initial state of the checkbox; does not change

$(elem).attr("checked") //(1.6.1+)
// "checked" (String) Will change with checkbox state

$(elem).attr("checked") //(pre-1.6)
// true (Boolean) Changed with checkbox state

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