user1476585
user1476585

Reputation: 81

How to know whether checkbox is checked or not, jquery?

Is there any better way to do this :

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

?

Upvotes: 1

Views: 435

Answers (4)

Denys Séguret
Denys Séguret

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

MBO
MBO

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

nbrooks
nbrooks

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

Aelios
Aelios

Reputation: 12147

$("input[type=checkbox]").is(":checked")

Upvotes: 2

Related Questions