Testing if a checkbox is checked with jQuery

04/10/2020 21:00:01

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:

<input type="checkbox" id="ans" value="1" />

Verified Answer (1008 Votes)

01/27/2011 11:03:59

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

More information here.


Answer #2 (210 Votes)

01/27/2011 11:05:59

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:


Answer #3 (90 Votes)

05/09/2012 16:47:53

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

It returns a boolean value.

Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.