Testing if a checkbox is checked with jQuery

Testing if a checkbox is checked with jQuery

If the checkbox is checked, then I only need to get the value as 1; otherwise, I need to get it as 0. How do I do this using jQuery?
$(“#ans”).val() will always give me one right in this case:


Solution 1:

Use .is(':checked') to determine whether or not it’s checked, and then set your value accordingly.

More information here.

Solution 2:


will tell you if it’s checked. You can also use a second parameter true/false to check/uncheck the checkbox.

$("#ans").attr('checked', true);

Per comment, use prop instead of attr when available. E.g:


Solution 3:

Just use $(selector).is(':checked')

It returns a boolean value.

Solution 4:

// use ternary operators
$("#ans").is(':checked') ? 1 : 0;

Solution 5:

Stefan Brinkmann’s answer is excellent, but incomplete for beginners (omits the variable assignment). Just to clarify:

// this structure is called a ternary operator
var cbAns = ( $("#ans").is(':checked') ) ? 1 : 0;

It works like this:

 var myVar = ( if test goes here ) ? 'ans if yes' : 'ans if no' ;


var myMath = ( 1 > 2 ) ? 'yes' : 'no' ;
alert( myMath );

Alerts ‘no’

If this is helpful, please upvote Stefan Brinkmann’s answer.

Solution 6:

You can try this: