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 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 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;
Sign up to request clarification or add additional context in comments.

1 Comment

.is() also returns true if at least one is checked. api.jquery.com/is
2
$("input[type=checkbox]").is(":checked")

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.