1476

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?

I am using the following code, but it always returns the count of checked checkboxes regardless of id.

function isCheckedById(id) {
    alert(id);
    var checked = $("input[@id=" + id + "]:checked").length;
    alert(checked);

    if (checked == 0) {
        return false;
    } else {
        return true;
    }
}
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Jake
  • 25,479
  • 31
  • 107
  • 168
  • 3
    a checkbox array means something like: etc.. – Jake Feb 05 '10 at 00:26
  • 2
    what's wrong with a checkbox array? how else would you do a "check all that apply" input? – nickf Feb 05 '10 at 00:27
  • 6
    Make sure your `id` s are unique! `name` can (and should, in this case) repeat, but you'll find a lot of weird things going on if you duplicate the `id`! =D – Jeff Rupert Feb 05 '10 at 00:40
  • ignore previous comment, it should be `return checked !== 0` – SuperStormer Jun 12 '17 at 19:08
  • Possible duplicate of [How to check whether a checkbox is checked in jQuery?](https://stackoverflow.com/questions/901712/how-to-check-whether-a-checkbox-is-checked-in-jquery) – Laurent S. Feb 14 '19 at 15:31
  • 1
    Does this answer your question? [How can I check if a checkbox is checked?](https://stackoverflow.com/questions/9887360/how-can-i-check-if-a-checkbox-is-checked) – Liam May 13 '22 at 13:51

27 Answers27

2423
$('#' + id).is(":checked")

That gets if the checkbox is checked.

For an array of checkboxes with the same name you can get the list of checked ones by:

var $boxes = $('input[name=thename]:checked');

Then to loop through them and see what's checked you can do:

$boxes.each(function(){
    // Do stuff here with this
});

To find how many are checked you can do:

$boxes.length;
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
John Boker
  • 82,559
  • 17
  • 97
  • 130
  • 2
    Another way is `$('#'+id).attr('checked')`, which is equivalent to `$('#' + id).is(":checked")` but easier to remember IMO. – Zubin Sep 03 '11 at 13:37
  • 91
    @Zubin: Be careful with `.attr('checked')`. Its behavior changed in jQuery 1.6. It used to return `false` or `true`. Now it returns `undefined` or `"checked"`. `.is(':checked')` does not have this problem. – Joey Adams Apr 07 '12 at 07:16
  • 1
    @John Boker: sorry for the necro comment but, why is it that `$('.ClassName').is(':checked')` doesn't seem to work but `$('#' + id).is(":checked")` does? aside from the fact that one looks up by id and one by classname. – Mike_OBrien Apr 16 '13 at 21:08
  • @John Boker: So if I know there will only ever be one element with a particular class name would treating the return from the class selector like an array work? meaning do something like: `$('.ClassName')[0].is(':checked')`? – Mike_OBrien Apr 18 '13 at 14:50
  • @Mike_OBrien Yes, but to get that one checkbox you'll have to do something like I have here http://jsfiddle.net/hYG4P/ – John Boker Apr 18 '13 at 18:38
  • 6
    Note: size() has been deprecated since jQuery 1.8 - use .length instead – JM4 Jul 09 '13 at 19:14
  • I agree with @Zubin about `.attr('checked')` since that will not work when testing `if($(this).attr('checked'))`but `if($(this).is(":checked"))` will work since it returns `true` or `false` . I had struggled with that on some old code where I upgraded jQuery version. This works fine now on jQuery 1.10. – Asle Jan 31 '16 at 22:27
  • 2
    $('#'+id).prop('checked') will return either true or false. – nbi Jul 20 '16 at 18:01
  • Gotta love easy answers like this one! – Rich Davis Nov 26 '18 at 17:38
  • This worked for me and seems more elegant or at least straightforward than the accepted answer. – Nathan Mar 21 '19 at 19:33
  • @Zubin **.attr('checked')** no longer corresponds to the _checked_ property. After jQuery v1.6, **.attr('checked')** returns the _defaultChecked_ property which is **True** if the checkbox _has_ a **checked** property - the **checked** property could be blank, true or false - **.attr('checked')** will still return True. So, one cannot get the job done with **.attr** any more. – Ankit Raj Goyal May 03 '22 at 04:32
782

IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;
nickf
  • 537,072
  • 198
  • 649
  • 721
  • 45
    Why use `$('#checkArray :checkbox:checked').length > 0;` when the more simple `$('#checkArray').checked` works and is available on more versions? – Don Cheadle Oct 27 '15 at 14:46
  • 5
    @Oddman it does work, just not on a jquery object. instead of $(elem).checked, try elem.checked. – Dan Williams Sep 01 '16 at 15:18
  • 1
    @DanWilliams yes but not in the example mmcrae gave. – Oddman Oct 20 '16 at 01:44
  • @AlejandroQuiroz I used to not omit the double quotes in jquery selector too. but recently I think it's quite useful because it improves code readibility and to avoid errors when the name or class contains a minus `-` sign – dapidmini Jun 26 '20 at 06:44
  • $('#checkArray').checked in chrome is giving "undefined" while document.getElementById('checkArray').checked gives true or false. – lisandro Jul 16 '23 at 15:59
367
$('#checkbox').is(':checked'); 

The above code returns true if the checkbox is checked or false if not.

Bellash
  • 7,560
  • 6
  • 53
  • 86
Prasanna Rotti
  • 3,671
  • 1
  • 13
  • 2
174

All following methods are useful:

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

$('#checkbox').prop('checked')

$('#checkbox')[0].checked

$('#checkbox').get(0).checked

It is recommended that DOMelement or inline "this.checked" should be avoided instead jQuery on method should be used event listener.

justnajm
  • 4,422
  • 6
  • 36
  • 56
113

jQuery code to check whether the checkbox is checked or not:

if($('input[name="checkBoxName"]').is(':checked'))
{
  // checked
}else
{
 // unchecked
}

Alternatively:

if($('input[name="checkBoxName"]:checked'))
{
    // checked
}else{
  // unchecked
}
Kundan roy
  • 3,082
  • 3
  • 18
  • 22
  • 4
    The first solution is missing `:`... Correct one is: `if(('input[name="checkBoxName"]').is(':checked'))`. – Aerendir Oct 19 '16 at 15:12
  • Missing dollar sign ($), it should be `if($('input[name="checkBoxName"]').is(':checked'))`. – Penny Liu Nov 08 '18 at 02:13
  • 1
    The second one will never run the `else` block, since a jQuery object, even if it contains no matching elements, is "truthy". Add `.length` to the end, then you're talking. – Heretic Monkey Aug 07 '19 at 18:56
  • Thanks! if($('input[name="checkBoxName"]').is(':checked')) is worked find, BUT $('input[name="checkBoxName"]:checked') didn't work. – OulinaArt Apr 26 '23 at 08:19
74

The most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property

All below methods are possible

elem.checked 

$(elem).prop("checked") 

$(elem).is(":checked") 
Techie
  • 44,706
  • 42
  • 157
  • 243
46

This is also an idea I use frequently:

var active = $('#modal-check-visible').prop("checked") ? 1 : 0 ;

If cheked, it'll return 1; otherwise it'll return 0.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Rtronic
  • 635
  • 5
  • 6
44

You can use this code,

if($("#checkboxId").is(':checked')){
     // Code in the case checkbox is checked.
} else {
     // Code in the case checkbox is NOT checked.
}
Mohammed Shaheen MK
  • 1,199
  • 10
  • 10
35

As per the jQuery documentation there are following ways to check if a checkbox is checked or not. Lets consider a checkbox for example (Check Working jsfiddle with all examples)

<input type="checkbox" name="mycheckbox" id="mycheckbox" />
<br><br>
<input type="button" id="test-with-checked" value="Test with checked" />
<input type="button" id="test-with-is" value="Test with is" />
<input type="button" id="test-with-prop" value="Test with prop" />

Example 1 - With checked

$("#test-with-checked").on("click", function(){
    if(mycheckbox.checked) {
        alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

Example 2 - With jQuery is, NOTE - :checked

var check;
$("#test-with-is").on("click", function(){
    check = $("#mycheckbox").is(":checked");
    if(check) {
        alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

Example 3 - With jQuery prop

var check;
$("#test-with-prop").on("click", function(){
    check = $("#mycheckbox").prop("checked");
    if(check) {
         alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

Check Working jsfiddle

Subodh Ghulaxe
  • 18,333
  • 14
  • 83
  • 102
31

I know the OP want jquery but in my case pure JS was the answer so if anyone like me is here and do not have jquery or do not want to use it - here is the JS answer:

document.getElementById("myCheck").checked

It returns true if the input with ID myCheck is checked and false if it is not checked.

Simple as that.

Combine
  • 3,894
  • 2
  • 27
  • 30
29

You can try this:

<script>
function checkAllCheckBox(value)
{
   if($('#select_all_').is(':checked')){
   $(".check_").attr ( "checked" ,"checked" );
    }
    else
    {
        $(".check_").removeAttr('checked');
    }

 }

</script>
<input type="checkbox" name="chkbox" id="select_all_" value="1" />


<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
Vishnu Sharma
  • 1,357
  • 12
  • 11
  • This is no longer a good way of doing things, as `attr` only reflects the attribute value in HTML, not the property value in the DOM. See [the documentation for `attr`](https://api.jquery.com/attr/), where it says "To retrieve and change DOM properties such as the `checked`, `selected`, or `disabled` state of form elements, use the `.prop()` method.", and [the documentation for `prop`](https://api.jquery.com/prop/), where it says "The `.prop()` method should be used to set `disabled` and `checked` instead of the `.attr()` method." – Heretic Monkey Aug 07 '19 at 19:02
24

You can use any of the following recommended codes by jquery.

if ( elem.checked ) {};
if ( $( elem ).prop( "checked" ) ) {};
if ( $( elem ).is( ":checked" ) ) {};
endur
  • 682
  • 11
  • 13
15
$(document).on('click','#checkBoxId',function(){
  var isChecked = $(this).is(':checked');
  console.log(isChecked);
});

This code above works also on bootstrap modal. isChecked is true or flase ;

infomasud
  • 2,263
  • 1
  • 18
  • 12
14

You can do it simply like;

Working Fiddle

HTML

<input id="checkbox" type="checkbox" />

jQuery

$(document).ready(function () {
    var ckbox = $('#checkbox');

    $('input').on('click',function () {
        if (ckbox.is(':checked')) {
            alert('You have Checked it');
        } else {
            alert('You Un-Checked it');
        }
    });
});

or even simpler;

$("#checkbox").attr("checked") ? alert("Checked") : alert("Unchecked");

If the checkbox is checked it will return true otherwise undefined

Aamir Shahzad
  • 6,683
  • 8
  • 47
  • 70
10

Simple Demo for checking and setting a check box.

jsfiddle!

$('.attr-value-name').click(function() {
    if($(this).parent().find('input[type="checkbox"]').is(':checked'))
    {
        $(this).parent().find('input[type="checkbox"]').prop('checked', false);
    }
    else
    {
        $(this).parent().find('input[type="checkbox"]').prop('checked', true);
    }
});
Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
An Illusion
  • 769
  • 1
  • 10
  • 24
10

Just to say in my example the situation was a dialog box that then verified the check box before closing dialog. None of above and How to check whether a checkbox is checked in jQuery? and jQuery if checkbox is checked did not appear to work either.

In the end

<input class="cb" id="rd" type="checkbox">
<input class="cb" id="fd" type="checkbox">

var fd=$('.cb#fd').is(':checked');
var rd= $('.cb#rd').is(':checked');

This worked so calling the class then the ID. rather than just the ID. It may be due to the nested DOM elements on this page causing the issue. The workaround was above.

Community
  • 1
  • 1
V H
  • 8,382
  • 2
  • 28
  • 48
9

For checkbox with an id

<input id="id_input_checkbox13" type="checkbox"></input>

you can simply do

$("#id_input_checkbox13").prop('checked')

you will get true or false as return value for above syntax. You can use it in if clause as normal boolean expression.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
9

Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!

Here are the syntaxes :

var checkbox = $('#'+id);
/* OR var checkbox = $("input[name=checkbox1]"); whichever is best */

/* The DOM way - The fastest */
if(checkbox[0].checked == true)
   alert('Checkbox is checked!!');

/* Using jQuery .prop() - The second fastest */
if(checkbox.prop('checked') == true)
   alert('Checkbox is checked!!');

/* Using jQuery .is() - The slowest in the lot */
if(checkbox.is(':checked') == true)
   alert('Checkbox is checked!!');

I personally prefer .prop(). Unlike .is(), It can also be used to set the value.

BlackPanther
  • 1,732
  • 1
  • 14
  • 19
8

Something like this can help

togglecheckBoxs =  function( objCheckBox ) {

    var boolAllChecked = true;

    if( false == objCheckBox.checked ) {
        $('#checkAll').prop( 'checked',false );
    } else {
        $( 'input[id^="someIds_"]' ).each( function( chkboxIndex, chkbox ) {
            if( false == chkbox.checked ) {
                $('#checkAll').prop( 'checked',false );
                boolAllChecked = false;
            }
        });

        if( true == boolAllChecked ) {
            $('#checkAll').prop( 'checked',true );
        }
    }
}
Abdul Hamid
  • 3,222
  • 3
  • 24
  • 31
8

Try this...

$(function(){
  $('body').on('click','.checkbox',function(e){
    
    if($(this).is(':checked')){
      console.log('Checked')
    } else {
      console.log('Unchecked')
    }
  })
})
oscar castellon
  • 3,048
  • 30
  • 19
6

Toggle checkbox checked

$("#checkall").click(function(){
    $("input:checkbox").prop( 'checked',$(this).is(":checked") );
})
sourceboy
  • 71
  • 1
  • 3
3

Using this code you can check at least one checkbox is selected or not in different checkbox groups or from multiple checkboxes. Using this you can not require to remove IDs or dynamic IDs. This code work with the same IDs.

Reference Link

<label class="control-label col-sm-4">Check Box 2</label>
    <input type="checkbox" name="checkbox2" id="checkbox21" value=ck1 /> ck1<br />
    <input type="checkbox" name="checkbox2" id="checkbox22" value=ck2 /> ck2<br />

<label class="control-label col-sm-4">Check Box 3</label>
    <input type="checkbox" name="checkbox3" id="checkbox31" value=ck3 /> ck3<br />
    <input type="checkbox" name="checkbox3" id="checkbox32" value=ck4 /> ck4<br />

<script>
function checkFormData() {
    if (!$('input[name=checkbox2]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
        return false;
    }
    if (!$('input[name=checkbox3]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
        return false;
    }
    alert("Success");
    return true;
}
</script>
Parth Patel
  • 799
  • 1
  • 13
  • 20
  • Basic information : html element ids not repeat ( eg: id="checkbox2", id="checkbox3" ). This is not a good practice. We can use class multiple times in a page. – Anand Somasekhar Apr 26 '18 at 11:53
3

Since it's mid 2019 and jQuery sometimes takes a backseat to things like VueJS, React etc. Here's a pure vanilla Javascript onload listener option:

<script>
  // Replace 'admincheckbox' both variable and ID with whatever suits.

  window.onload = function() {
    const admincheckbox = document.getElementById("admincheckbox");
    admincheckbox.addEventListener('click', function() {
      if(admincheckbox.checked){
        alert('Checked');
      } else {
        alert('Unchecked');
      }
    });
  }
</script>
Grant
  • 5,709
  • 2
  • 38
  • 50
3

Your question is not clear: you want to give "checkbox array id" at input and get true/false at output - in this way you will not know which checkbox was checked (as your function name suggest). So below there is my proposition of body of your isCheckedById which on input take checkbox id and on output return true/false (it's very simple but your ID should not be keyword),

this[id].checked

function isCheckedById(id) {
  return this[id].checked;
}



// TEST

function check() {
  console.clear()
  console.log('1',isCheckedById("myCheckbox1"));
  console.log('2',isCheckedById("myCheckbox2"));
  console.log('3',isCheckedById("myCheckbox3"));
}
<label><input id="myCheckbox1" type="checkbox">check 1</label>
<label><input id="myCheckbox2" type="checkbox">check 2</label>
<label><input id="myCheckbox3" type="checkbox">check 3</label>
<!-- label around inputs makes text clickable -->
<br>
<button onclick="check()">show checked</button>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
1

You can try either any of the ways preferred, as in jQuery or JavaScript.

Get the value as below and assign to the variable then you if-else statements as per your requirement.

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

var getVal=document.getElementById("checkbox_id").checked //JavaScript

if (getVal==true) {
 // perform task
} else {
 // perform task 
}
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
0

Just use the [0] index of the jquery object, and checked will work.

$(elem)[0].checked
lisandro
  • 454
  • 4
  • 12
-6

use code below

<script>

$(document).ready(function () {
  $("[id$='chkSendMail']").attr("onchange", "ShowMailSection()");
}

function ShowMailSection() {
  if ($("[id$='chkSendMail'][type='checkbox']:checked").length >0){
      $("[id$='SecEmail']").removeClass("Hide");
  }
</script>
Sp0T
  • 284
  • 8
  • 23
Code_Worm
  • 4,069
  • 2
  • 30
  • 35