704

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

Joel Beckham
  • 18,254
  • 3
  • 35
  • 58
maztt
  • 12,278
  • 21
  • 78
  • 153

21 Answers21

1344

To check whether it is checked or not, do:

if ($('#check_id').is(":checked"))
{
  // it is checked
}

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.

Marco Sulla
  • 15,299
  • 14
  • 65
  • 100
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 186
    If I try `$($0).val()` in Chrome, and untick the checkbox, the answer is "on" even though it is not ticked. But `$($0).is(":checked")` returns the right value. – Adrien Dec 12 '13 at 10:52
  • upvoted wrong answer . realizing its indeed `on` always a bit later – CodeToLife Feb 19 '22 at 00:07
  • 5
    Sorry, but this answer literally wasted around 1 hour of my time. All checkboxes are "on" with using `.val();` I'm strongly suggesting to use `.is(":checked")` to anyone reading this! – Banik May 08 '22 at 10:42
290

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" />
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
68

Try this small solution:

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

or

$("#some_id").attr("checked") || 0;
RDK
  • 4,540
  • 2
  • 20
  • 29
56

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/

Reza
  • 665
  • 6
  • 8
  • 1
    `.is(":checked")` and `.prop(":checked")` are working the same for me w/ jQuery 1.10.0 – Josh Nov 10 '17 at 19:05
  • @Josh, you are right thanks! I updated the answer to clarify for future readers. – Reza Aug 06 '20 at 09:24
29

Just to clarify things:

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

Will return 'true' or 'false'

Greg A
  • 531
  • 4
  • 9
22
$('#checkbox_id').val();
$('#checkbox_id').is(":checked");
$('#checkbox_id:checked').val();
Nalan Madheswaran
  • 10,136
  • 1
  • 57
  • 42
19

Simple but effective and assumes you know the checkbox will be found:

$("#some_id")[0].checked;

Gives true/false

Kevin Shea
  • 920
  • 7
  • 12
17
//By each()
var testval = [];
 $('.hobbies_class:checked').each(function() {
   testval.push($(this).val());
 });


//by map()
var testval = $('input:checkbox:checked.hobbies_class').map(function(){
return this.value; }).get().join(",");

 //HTML Code

 <input type="checkbox" value="cricket" name="hobbies[]"  class="hobbies_class">Cricket 
  <input type="checkbox" value="hockey" name="hobbies[]" class="hobbies_class">Hockey

Example
Demo

Kamal
  • 796
  • 7
  • 11
11
jQuery(".checkboxClass").click(function(){
        var selectedCountry = new Array();
        var n = jQuery(".checkboxClass:checked").length;
        if (n > 0){
            jQuery(".checkboxClass:checked").each(function(){
                selectedCountry.push($(this).val());
            });
        }
        alert(selectedCountry);
    });
Jaskaran singh Rajal
  • 2,270
  • 2
  • 17
  • 29
7
$("input[name='gender']:checked").val();

this worked in my case, anyone looking for a simple way, must try this syntax. Thanks

Tayyab Hayat
  • 815
  • 1
  • 9
  • 22
6

Despite the fact that this question is asking for a jQuery solution, here is a pure JavaScript answer since nobody has mentioned it.

Without jQuery:

Simply select the element and access the checked property (which returns a boolean).

var checkbox = document.querySelector('input[type="checkbox"]');

alert(checkbox.checked);
<input type="checkbox"/>

Here is a quick example listening to the change event:

var checkbox = document.querySelector('input[type="checkbox"]');
checkbox.addEventListener('change', function (e) {
    alert(this.checked);
});
<input type="checkbox"/>

To select checked elements, use the :checked pseudo class (input[type="checkbox"]:checked).

Here is an example that iterates over checked input elements and returns a mapped array of the checked element's names.

Example Here

var elements = document.querySelectorAll('input[type="checkbox"]:checked');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);

var elements = document.querySelectorAll('input[type="checkbox"]:checked');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);
<div class="parent">
    <input type="checkbox" name="name1" />
    <input type="checkbox" name="name2" />
    <input type="checkbox" name="name3" checked="checked" />
    <input type="checkbox" name="name4" checked="checked" />
    <input type="checkbox" name="name5" />
</div>
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
5

You could use the following. It is tested working OK.

$('#checkbox_id').is(":checked"); // jQuery

if checkbox is checked this will return true and vice versa.

This below code fragment is for anyone trying to do the same in JavaScript.

document.getElementById("checkbox_id").checked //JavaScript

return true if checkbox is checked

Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
3

Here is how to get the value of all checked checkboxes as an array:

var values = (function() {
                var a = [];
                $(".checkboxes:checked").each(function() {
                    a.push(this.value);
                });
                return a;
            })()
Faraz Kelhini
  • 3,925
  • 32
  • 38
2

Use the following code:

$('input[name^=CheckBoxInput]').val();
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
Myint Thu Lwin
  • 229
  • 1
  • 3
  • 8
2

to get value of checked checkboxex in jquery:

var checks = $("input[type='checkbox']:checked"); // returns object of checkeds.

for(var i=0; i<checks.length; i++){
    console.log($(checks[i]).val()); // or do what you want
});

in pure js:

var checks = document.querySelectorAll("input[type='checkbox']:checked");

for(var i=0; i<checks.length; i++){
    console.log(checks[i].value); // or do what you want
});
ttrasn
  • 4,322
  • 4
  • 26
  • 43
0
$('.class[value=3]').prop('checked', true);
Pang
  • 9,564
  • 146
  • 81
  • 122
  • 1
    The question is asking how to *get the value* not how to check something with a particular default value. – Quentin Jun 22 '19 at 11:44
0

Best way is $('input[name="line"]:checked').val()

And also you can get selected text $('input[name="line"]:checked').text()

Add value attribute and name to your radio button inputs. Make sure all inputs have same name attribute.

<div class="col-8 m-radio-inline">
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="1" checked> Value Text 1
    </label>
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="2"> Value Text 2
    </label>
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="3"> Value Text 3
    </label>
</div>
Hayrullah Cansu
  • 262
  • 5
  • 14
0

For more than 1 checkbox always use named array as show in the below example with countries, as you know countries can be selected multiple so I used name="countries[]" and while checking checkboxes you have to reference it by name as shown in below example

var selectedCountries = ["Pakistan", "USA"];

$(document).ready(function () {
  $.each(selectedCountries, function (index, country) {
    $(`input[name='countries[]'][value='${country}']`).attr('checked', 'checked');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>
  <input type="checkbox" name="countries[]" value="Pakistan">
  Pakistan
</p>
<p>
  <input type="checkbox" name="countries[]" value="India">
  India
</p>
<p>
  <input type="checkbox" name="countries[]" value="USA">
  USA
</p>
Tahir Afridi
  • 190
  • 3
  • 14
0

If only one child is expected to be selected:

form.querySelector(":checked").value
Franc Jerez
  • 113
  • 3
  • 5
-1
<script type="text/javascript">
$(document).ready(function(){
    $('.laravel').click(function(){
        var val = $(this).is(":checked");
        $('#category').submit();
    });
});

<form action="{{route('directory')}}" method="post" id="category">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                        <input name="category" value="{{$name->id}}"  class="laravel" type="checkbox">{{$name->name}}
                      </form>
Kuldeep Mishra
  • 3,846
  • 1
  • 21
  • 26
-1

Just attention, as of today, 2018, due to api changing over the years. removeAttr are depricated, NOT working anymore!

Jquery Check or unCheck a checkbox:

Bad, not working any more.

   $('#add_user_certificate_checkbox').removeAttr("checked");

   $('#add_user_certificate_checkbox').attr("checked","checked");

Instead you should do:

      $('#add_user_certificate_checkbox').prop('checked', true);
      $('#add_user_certificate_checkbox').prop('checked', false);
hoogw
  • 4,982
  • 1
  • 37
  • 33