Advertisement
Advertisement


Get checkbox value in jQuery


Question

How can I get a checkbox's value in jQuery?

2011/11/01
1
551
11/1/2011 5:50:18 PM

Accepted Answer

To get the value of the Value attribute you can do something like this:

$("input[type='checkbox']").val();

Or if you have set a class or id for it, you can:

$('#check_id').val();
$('.check_class').val();

However this will return the same value whether it is checked or not, this can be confusing as it is different to the submitted form behaviour.

To check whether it is checked or not, do:

if ($('#check_id').is(":checked"))
{
  // it is checked
}
2018/12/24
1091
12/24/2018 9:01:18 AM

Those 2 ways are working:

  • $('#checkbox').prop('checked')
  • $('#checkbox').is(':checked') (thanks @mgsloan)

$('#test').click(function() {
    alert("Checkbox state (method 1) = " + $('#test').prop('checked'));
    alert("Checkbox state (method 2) = " + $('#test').is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Check me: <input id="test" type="checkbox" />

2015/01/01

Try this small solution:

$("#some_id").attr("checked") ? 1 : 0;

or

$("#some_id").attr("checked") || 0;
2014/06/10

The best way of retrieving a checkbox's value is as following

if ( elem.checked ) 
if ( $( elem ).prop( "checked" ) ) 
if ( $( elem ).is( ":checked" ) ) 

as explained in the official documentations in jQuery's website. The rest of the methods has nothing to do with the property of the checkbox, they are checking the attribute which means they are testing the initial state of the checkbox when it was loaded. So in short:

  • When you have the element and you know it is a checkbox you can simply read its property and you won't need jQuery for that (i.e. elem.checked) or you can use $(elem).prop("checked") if you want to rely on jQuery.
  • If you need to know (or compare) the value when the element was first loaded (i.e. the default value) the correct way to do it is elem.getAttribute("checked") or elem.prop("defaultChecked").

Please note that elem.attr("checked") is modified only after version 1.6.1+ of jQuery to return the same result as elem.prop("checked").

Some answers are misleading or imprecise, Please check below yourself:

http://api.jquery.com/prop/

2020/08/06

Just to clarify things:

$('#checkbox_ID').is(":checked")

Will return 'true' or 'false'

2015/04/26

$('#checkbox_id').val();
$('#checkbox_id').is(":checked");
$('#checkbox_id:checked').val();
2017/07/15

Source: https://stackoverflow.com/questions/2834350
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]