Reputation: 81
Is there any better way to do this :
var IsC = $('input[type=checkbox]').attr("checked") == "checked" ? true : false;
?
Upvotes: 1
Views: 435
Reputation: 382464
You can use the :checked selector
var IsC = $('input[type=checkbox]').is(":checked");
Or :
var IsC = $('input[type=checkbox]:checked').length>0;
Upvotes: 4
Reputation: 31025
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
Upvotes: 0
Reputation: 18233
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');
Upvotes: 1