5148

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.

But the following code returns false by default:

if ($('#isAgeSelected').attr('checked')) {
  $("#txtAge").show();
} else {
  $("#txtAge").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">
  Age is selected
</div>

How do I successfully query the checked property?

Anonymous
  • 738
  • 4
  • 14
  • 36
Prasad
  • 58,881
  • 64
  • 151
  • 199
  • 6
    Starting jquery 1.6 there have been significant changes the way attributes and properties are dealt with. For your case following should work: if($('#isAgeSelected').prop("checked")) { $("#txtAge").show(); } else { $("#txtAge").hide(); } The condition in if statement will simply return true or false depending upon the checked/unchecked state of the check box. For more details refer to attributes vs. properties section on [this](http://api.jquery.com/prop/) link. – RBT Feb 12 '16 at 18:44
  • 3
    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

68 Answers68

3661

How do I successfully query the checked property?

The checked property of a checkbox DOM element will give you the checked state of the element.

Given your existing code, you could therefore do this:

if(document.getElementById('isAgeSelected').checked) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

However, there's a much prettier way to do this, using toggle:

$('#isAgeSelected').click(function() {
    $("#txtAge").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 136
    This is not an answer to the question. `this.checked` is not jQuery, as the OP asked for. Also, it only works when user clicks on the checkbox, which is not part of the question. The question is, again, `How to check whether a checkbox is checked in jQuery?` at any given time with or without clicking the checkbox and in jQuery. – Marc Compte Jul 06 '17 at 10:58
  • How would “is not jQuery” be an argument? That attitude is quite harmful and the reason why it’s so hard to get rid of jQuery nowadays! If you can use vanilla JavaScript from ages ago, which works everywhere and is in no way more complicated to use or longer to write, you should definitely do so. – Andy Aug 05 '22 at 10:55
  • Not only that but jquery is a javascript extension, and therefore contains all of javascript. . In any case "this" is a jquery object so he's completely wrong anyway. – John Lord Sep 07 '22 at 22:00
  • "How would 'is not jquery' be an argument?" Because, while you can indeed use both jquery and plain js on the same script, it's more readable if you use *one* coding style rather than two. And if you already accepted the jquery tradeoffs, you may as well use it. – Adriano Varoli Piazza May 03 '23 at 14:24
2227

Use jQuery's is() function:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Bhanu Krishnan
  • 3,726
  • 1
  • 20
  • 40
647

Using jQuery > 1.6

<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />

// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true

Using the new property method:

if($('#checkMeOut').prop('checked')) {
    // something when checked
} else {
    // something else when not
}
SeanDowney
  • 17,368
  • 20
  • 81
  • 90
  • 1
    Doesn't work if you have a `` alongside the checkbox like several frameworks do in order to always submit a value. `.is(':checked')` on the other hand works in that case. – TheStoryCoder Nov 26 '21 at 11:53
271

jQuery 1.6+

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

jQuery 1.5 and below

$('#isAgeSelected').attr('checked')

Any version of jQuery

// Assuming an event handler on a checkbox
if (this.checked)

All credit goes to Xian.

Community
  • 1
  • 1
ungalcrys
  • 5,242
  • 2
  • 39
  • 23
  • 12
    Technically, `this.checked` is using straight Javascript. But I love that cross-jQuery-version answer! – vapcguy Jun 19 '15 at 16:50
  • 1
    Doesn't work if you have a `` alongside the checkbox like several frameworks do in order to always submit a value. `.is(':checked')` on the other hand works in that case. – TheStoryCoder Nov 26 '21 at 11:54
193

I am using this and this is working absolutely fine:

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

Note: If the checkbox is checked it will return true otherwise undefined, so better check for the "TRUE" value.

srikanth_yarram
  • 957
  • 9
  • 16
Pradeep
  • 417
  • 1
  • 5
  • 2
177

Use:

<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

$("#planned_checked").change(function() {
    if($(this).prop('checked')) {
        alert("Checked Box Selected");
    } else {
        alert("Checked Box deselect");
    }
});

    $("#planned_checked").change(function() {
        if($(this).prop('checked')) {
            alert("Checked Box Selected");
        } else {
            alert("Checked Box deselect");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned
Samuel Méndez
  • 601
  • 10
  • 18
Lalji Dhameliya
  • 1,729
  • 1
  • 17
  • 26
135

Since jQuery 1.6, the behavior of jQuery.attr() has changed and users are encouraged not to use it to retrieve an element's checked state. Instead, you should use jQuery.prop():

$("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
                                        // Return value changes with checkbox state
);

Two other possibilities are:

$("#txtAge").get(0).checked
$("#txtAge").is(":checked")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Salman A
  • 262,204
  • 82
  • 430
  • 521
116

This worked for me:

$get("isAgeSelected ").checked == true

Where isAgeSelected is the id of the control.

Also, @karim79's answer works fine. I am not sure what I missed at the time I tested it.

Note, this is answer uses Microsoft Ajax, not jQuery

Community
  • 1
  • 1
Prasad
  • 58,881
  • 64
  • 151
  • 199
109

If you are using an updated version of jquery, you must go for .prop method to resolve your issue:

$('#isAgeSelected').prop('checked') will return true if checked and false if unchecked. I confirmed it and I came across this issue earlier. $('#isAgeSelected').attr('checked') and $('#isAgeSelected').is('checked') is returning undefined which is not a worthy answer for the situation. So do as given below.

if($('#isAgeSelected').prop('checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85
75

Use:

<input type="checkbox" id="abc" value="UDB">UDB
<input type="checkbox" id="abc" value="Prasad">Prasad
$('input#abc').click(function(){
  if($(this).is(':checked'))
  {
    var checkedOne=$(this).val()
    alert(checkedOne);

    // Do some other action
  }
})

This can help if you want that the required action has to be done only when you check the box not at the time you remove the check.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
Udit Bhardwaj
  • 1,761
  • 1
  • 19
  • 29
71

You can try the change event of checkbox to track the :checked state change.

$("#isAgeSelected").on('change', function() {
  if ($("#isAgeSelected").is(':checked'))
    alert("checked");
  else {
    alert("unchecked");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected" />
<div id="txtAge" style="display:none">
  Age is selected
</div>
kabirbaidhya
  • 3,264
  • 3
  • 34
  • 59
Ajay Katariya
  • 439
  • 9
  • 22
70

Using the Click event handler for the checkbox property is unreliable, as the checked property can change during the execution of the event handler itself!

Ideally, you'd want to put your code into a change event handler such as it is fired every time the value of the check box is changed (independent of how it's done so).

$('#isAgeSelected').bind('change', function () {

   if ($(this).is(':checked'))
     $("#txtAge").show();
   else
     $("#txtAge").hide();
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
arviman
  • 5,087
  • 41
  • 48
64

I ran in to the exact same issue. I have an ASP.NET checkbox

<asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />

In the jQuery code I used the following selector to check if the checkbox was checked or not, and it seems to work like a charm.

if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

I'm sure you can also use the ID instead of the CssClass,

if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

I hope this helps you.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nertim
  • 380
  • 6
  • 15
  • you _can_ use the css class, as long as you keep in mind that css classes aren't meant to be unique. If you want to respond to changes in a single element then ID would be the preffered way to go. – Kemuel Sanchez Sep 08 '21 at 00:20
62

I believe you could do this:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}
xenon
  • 1,435
  • 19
  • 35
  • This is the best answer for selecting ONLY those that are checked in the first place. $('#isAgeSelected :checked') – Kevin Dark Oct 14 '21 at 15:41
62

I decided to post an answer on how to do that exact same thing without jQuery. Just because I'm a rebel.

var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');

// Just because of IE <333
ageCheckbox.onchange = function() {
    // Check if the checkbox is checked, and show/hide the text field.
    ageInput.hidden = this.checked ? false : true;
};

First you get both elements by their ID. Then you assign the checkboxe's onchange event a function that checks whether the checkbox got checked and sets the hidden property of the age text field appropriately. In that example using the ternary operator.

Here is a fiddle for you to test it.

Addendum

If cross-browser compatibility is an issue then I propose to set the CSS display property to none and inline.

elem.style.display = this.checked ? 'inline' : 'none';

Slower but cross-browser compatible.

Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
60

This code will help you

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});
Sandeep Sherpur
  • 2,418
  • 25
  • 27
57

This works for me:

/* isAgeSelected being id for checkbox */

$("#isAgeSelected").click(function(){
  $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ashish amatya
  • 59
  • 2
  • 2
53

There are many ways to check if a checkbox is checked or not:

Way to check using jQuery

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

Check example or also document:

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Parth Chavda
  • 1,819
  • 1
  • 23
  • 30
49

This is some different method to do the same thing:

$(document).ready(function (){

    $('#isAgeSelected').click(function() {
        // $("#txtAge").toggle(this.checked);

        // Using a pure CSS selector
        if ($(this.checked)) {
            alert('on check 1');
        };

        // Using jQuery's is() method
        if ($(this).is(':checked')) {
            alert('on checked 2');
        };

        //  // Using jQuery's filter() method
        if ($(this).filter(':checked')) {
            alert('on checked 3');
        };
    });
});
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sangeet Shah
  • 3,079
  • 2
  • 22
  • 25
43

Use this:

if ($('input[name="salary_in.Basic"]:checked').length > 0)

The length is greater than zero if the checkbox is checked.

Michael Yousrie
  • 1,132
  • 2
  • 10
  • 20
Hamid N K
  • 87
  • 2
  • 7
39

My way of doing this is:

if ( $("#checkbox:checked").length ) {       
    alert("checkbox is checked");
} else {
    alert("checkbox is not checked");
}
potashin
  • 44,205
  • 11
  • 83
  • 107
Dalius I
  • 943
  • 11
  • 6
36
$(selector).attr('checked') !== undefined

This returns true if the input is checked and false if it is not.

fe_lix_
  • 938
  • 11
  • 18
35

You can use:

  if(document.getElementById('isAgeSelected').checked)
    $("#txtAge").show();  
  else
    $("#txtAge").hide();

if($("#isAgeSelected").is(':checked'))
  $("#txtAge").show();  
else
  $("#txtAge").hide();

Both of them should work.

Jogi
  • 1
  • 2
  • 14
  • 29
Muhammad Awais
  • 4,238
  • 1
  • 42
  • 37
34
$(document).ready(function() {    
    $('#agecheckbox').click(function() {
        if($(this).is(":checked"))
        {
            $('#agetextbox').show();
        } else {
            $('#agetextbox').hide();
        }
    });
});
René Sackers
  • 2,395
  • 4
  • 24
  • 43
Jasper
  • 363
  • 5
  • 10
32

1) If your HTML markup is:

<input type="checkbox"  />

attr used:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

If prop is used:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2) If your HTML markup is:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"

attr used:

$(element).attr("checked") // Will return checked whether it is checked="true"

Prop used:

$(element).prop("checked") // Will return true whether checked="checked"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Somnath Kharat
  • 3,570
  • 2
  • 27
  • 51
  • This is a REAL problem. My workaround - add a change event to the input: then use that event to change a boolean JavaScript variable, and use the JavaScript variable instead of querying the checkbox directly. – Graham Laight May 10 '16 at 11:33
28

The top answer didn't do it for me. This did though:

<script type="text/javascript">
    $(document).ready(function(){

        $("#li_13").click(function(){
            if($("#agree").attr('checked')){
                $("#saveForm").fadeIn();
            }
            else
            {
                $("#saveForm").fadeOut();
            }
        });
    });
</script>

Basically when the element #li_13 is clicked, it checks if the element # agree (which is the checkbox) is checked by using the .attr('checked') function. If it is then fadeIn the #saveForm element, and if not fadeOut the saveForm element.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MDMoore313
  • 3,233
  • 1
  • 23
  • 38
28

This example is for button.

Try the following:

<input type="button" class="check" id="checkall" value="Check All" />  &nbsp; <input type="button" id="remove" value="Delete" /> <br/>

<input type="checkbox" class="cb-element"  value="1" /> Checkbox  1 <br/>
<input type="checkbox" class="cb-element"  value="2" /> Checkbox  2 <br/>
<input type="checkbox" class="cb-element"  value="3" /> Checkbox  3 <br/>


$('#remove').attr('disabled', 'disabled'); 

$(document).ready(function() {  

    $('.cb-element').click(function() {

        if($(this).prop('checked'))
        {
            $('#remove').attr('disabled', false);
        }
        else
        {
            $('#remove').attr('disabled', true);
        }
    });   

    $('.check:button').click(function()
{
    var checked = !$(this).data('checked');
    $('input:checkbox').prop('checked', checked);
    $(this).data('checked', checked);

    if(checked == true)
    {
        $(this).val('Uncheck All');
         $('#remove').attr('disabled', false);
    }

    else if(checked == false)
    {
        $(this).val('Check All');
        $('#remove').attr('disabled', true);
    }
});
});
Ulf Gjerdingen
  • 1,414
  • 3
  • 16
  • 20
usayee
  • 59
  • 3
  • 8
28

To act on a checkbox being checked or unchecked on click.

$('#customCheck1').click(function() {
  if (this.checked) {
    console.log('checked');
  } else {
    console.log('un-checked');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

EDIT: Not a nice programming expression if (boolean == true) though .checked property might return other type variables as well..

It is better to use .prop("checked") instead. It returns true and false only.

kabirbaidhya
  • 3,264
  • 3
  • 34
  • 59
Dan Walters
  • 1,218
  • 1
  • 18
  • 30
  • Note that `this.checked` will **not work on a Jquery object** as outlined [here](https://stackoverflow.com/a/21123921/1526703). [This](https://stackoverflow.com/a/58215046/1526703) would work (i.e `$(this).is(":checked")`) – Anupam Oct 14 '21 at 06:49
27

I am using this:

 <input type="checkbox" id="isAgeSelected" value="1" /> <br/>
 <input type="textbox" id="txtAge" />

 $("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nishant Kumar
  • 5,995
  • 19
  • 69
  • 95
27

Though you have proposed a JavaScript solution for your problem (displaying a textbox when a checkbox is checked), this problem could be solved just by css. With this approach, your form works for users who have disabled JavaScript.

Assuming that you have the following HTML:

<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />

You can use the following CSS to achieve the desired functionality:

 #show_textbox:not(:checked) + input[type=text] {display:none;}

For other scenarios, you may think of appropriate CSS selectors.

Here is a Fiddle to demonstrate this approach.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ormoz
  • 2,975
  • 10
  • 35
  • 50
24

Toggle: 0/1 or else

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

    $('#nolunch').change(function () {
    if ($(this).is(':checked')) {
        $('#checklunch').val('1');
    };
    if ($(this).is(':checked') == false) {
        $('#checklunch').val('0');
    };
});
Jez D
  • 1,461
  • 2
  • 25
  • 52
Bram
  • 49
  • 2
  • 11
23

I think it will be the simple one

$('#isAgeSelected').change(function() {
    if($(this).is(":checked")) {
        $('#txtAge').show();
    }
else{
        $('#txtAge').hide();
    }                                          
});
Jitendra Damor
  • 774
  • 17
  • 27
22

Please try below code to check checkbox is checked or not

$(document).ready(function(){

    $("#isAgeSelected").on('change',function(){

    if($("#isAgeSelected").is(':checked'))
        $("#txtAge").show();  // checked
    else{
        $("#txtAge").hide();  // unchecked
    }

   });

});
mrfizh
  • 121
  • 1
  • 9
Javed Khan
  • 395
  • 5
  • 9
20

I'm sure it's not some revelation, but I didn't see it all in one example:

Selector for all checked checkboxes(on the page):

$('input[type=checkbox]:checked')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tsonev
  • 435
  • 7
  • 17
19

I verified in Firefox 9.0.1 that the following works for catching the state of a checkbox post change:

$("#mycheckbox").change(function() {
    var value = $(this).prop("checked") ? 'true' : 'false';                     
    alert(value);
});
Joshua Harris
  • 409
  • 5
  • 9
17

Include jQuery from the local file system. I used Google's CDN, and there are also many CDNs to choose from.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

The code will execute as soon as a checkbox inside mycheck class is clicked. If the current clicked checkbox is checked then it will disable all others and enable the current one. If the current one is unchecked, it will again enable all checkboxes for rechecking.

<script type="text/javascript">
    $(document).ready(function() {

        var checkbox_selector = '.mycheck input[type=checkbox]';

        $(checkbox_selector).click(function() {
            if ($($(this)).is(':checked')) {

                // Disable all checkboxes
                $(checkbox_selector).attr('disabled', 'disabled');

                // Enable current one
                $($(this)).removeAttr('disabled');
            }
            else {
                // If unchecked open all checkbox
                $(checkbox_selector).removeAttr('disabled');
            }
        });
    });
</script>

Simple form to test

<form method="post" action="">
    <div class="mycheck">
        <input type="checkbox" value="1" /> Television
        <input type="checkbox" value="2" /> Computer
        <input type="checkbox" value="3" /> Laptop
        <input type="checkbox" value="4" /> Camera
        <input type="checkbox" value="5" /> Music Systems
    </div>
</form>

Output screen:

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Madan Sapkota
  • 25,047
  • 11
  • 113
  • 117
17
if($("#checkkBoxId").is(':checked')){
  alert("Checked=true");
}

or

if($("#checkkBoxId").attr('checked') == true){
  alert("checked=true");
}
ijarlax
  • 515
  • 2
  • 12
  • 18
15

The checked attribute of an input type="checkbox" is mapped with the defaultChecked property, not with the checked property.

So when doing something in a page when a checkbox is checked on uncheked, use the prop() method instead. It fetches the property value and changes as the state of the checkbox changes.

Using attr() or getAttribute(in pure JavaScript) in these cases are not the proper way of doing things.

if elem is the concerned checkbox then do something like this to fetch the value:

elem.checked

or

$(elem).prop('checked')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
subham.saha1004
  • 794
  • 8
  • 6
15

Automated

$(document).ready(function()
{
    $('#isAgeSelected').change(function()
    {
        alert( 'value =' + $('#chkSelect').attr('checked') );
    });
});

HTML

<b> <input type="isAgeSelected" id="chkSelect" /> Age Check </b>

<br/><br/>

<input type="button" id="btnCheck" value="check" />

jQuery

$(document).ready(function()
{
    $('#btnCheck').click(function()
    {
        var isChecked = $('#isAgeSelected').attr('checked');

        if (isChecked == 'checked')
            alert('check-box is checked');
        else
            alert('check-box is not checked');
    })
});

Ajax

function check()
{
    if (isAgeSelected())
        alert('check-box is checked');
    else
        alert('check-box is not checked');
}

function isAgeSelected()
{
    return ($get("isAgeSelected").checked == true);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Khaled.K
  • 5,828
  • 1
  • 33
  • 51
14

This is the minimal amount of code I think I needed to do something like this effectively. I found this method to be useful; it returns an array of the check boxes that are checked and then you can use their value (this solution uses jQuery):

// This is how you get them
var output = "";
var checkedBoxes = $("DivCheckBoxesAreIn").children("input:checked");
if(checkedBoxes.length <= 0) {
    alert('Please select check boxes');
    return false;
};

// And this is how you use them:
checkedBoxes.each(function() {
    output +=  this.value + ", ";
};

Printing "output" will give you a comma-separated list of your values.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daryl H
  • 624
  • 8
  • 8
14

$(document).on("click","#isAgeSelected",function(){
  if($(this).prop("checked") == true){
    $("#txtAge").show();
  }
  else if($(this).prop("checked") == false){
    $("#txtAge").hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

<div id="txtAge" style="display:none">
<input type="text" name="age" placeholder="Please enter age" />
</div>
ROOT
  • 11,363
  • 5
  • 30
  • 45
Sarvesh Patel
  • 133
  • 1
  • 3
  • 12
13

I was having the same problem and none of the posted solutions seemed to work and then I found out that it's because ASP.NET renders the CheckBox control as a SPAN with INPUT inside, so the CheckBox ID is actually an ID of a SPAN, not an INPUT, so you should use:

$('#isAgeSelected input')

rather than

$('#isAgeSelected')

and then all methods listed above should work.

tsw_mik
  • 77
  • 1
  • 3
13

Simply use it like below

 $('#isAgeSelected').change(function() {
     if ($(this).is(":checked")) { // or if($("#isAgeSelected").attr('checked') == true){
         $('#txtAge').show();
     } else {
         $('#txtAge').hide();
     }
 });
Mayank
  • 1,351
  • 5
  • 23
  • 42
13

Using pure JavaScript:

let checkbox = document.getElementById('checkboxID');

if(checkbox.checked) {
  alert('is checked');
} else {
  alert('not checked yet');
}
Alex Lussier
  • 113
  • 1
  • 9
Abraham
  • 8,525
  • 5
  • 47
  • 53
13

Here's an example that includes initialising the show/hide to match the state of the checkbox when the page loads; taking account of the fact that firefox remembers the state of checkboxes when you refresh the page, but won't remember the state of the shown/hidden elements.

$(function() {
    // initialise visibility when page is loaded
    $('tr.invoiceItemRow').toggle($('#showInvoiceItems').attr('checked'));
    // attach click handler to checkbox
    $('#showInvoiceItems').click(function(){ $('tr.invoiceItemRow').toggle(this.checked);})
});

(with help from other answers on this question)

Tim Abell
  • 11,186
  • 8
  • 79
  • 110
10

This was my workaround:

$('#vcGoButton').click(function () {
    var buttonStatus = $('#vcChangeLocation').prop('checked');
    console.log("Status is " + buttonStatus);
    if (buttonStatus) {
        var address = $('#vcNewLocation').val();
        var cabNumber = $('#vcVehicleNumber').val();
        $.get('postCabLocation.php',
              {address: address, cabNumber: cabNumber},
              function(data) {
                  console.log("Changed vehicle " + cabNumber + " location to " + address );
              });
    }
    else {
        console.log("VC go button clicked, but no location action");
    }
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cauleyfj
  • 21
  • 1
  • 2
9

Use:

$(this).toggle($("input:checkbox", $(this))[0].checked);

When you are selecting out of context, remember you need the [0] to access the checkbox.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Richard Maxwell
  • 508
  • 5
  • 7
9

Setter:

$("#chkmyElement")[0].checked = true;

Getter:

if($("#chkmyElement")[0].checked) {
   alert("enabled");
} else {
   alert("disabled");
}
JJ_Coder4Hire
  • 4,706
  • 1
  • 37
  • 25
8

I would actually prefere the change event.

$('#isAgeSelected').change(function() {
    $("#txtAge").toggle(this.checked);
});

Demo Fiddle

RevanthKrishnaKumar V.
  • 1,855
  • 1
  • 21
  • 34
Tarion
  • 16,283
  • 13
  • 71
  • 107
8

A selector returns multiple objects, and it must take the first item in the array:

// Collection
var chckremember = $("#chckremember");


// Result boolen
var ischecked=chckremember[0].checked;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
zamoldar
  • 548
  • 10
  • 13
8

Try this,

$('#isAgeSelected').click(function() {
    if(this.checked){
        $("#txtAge").show();
    } else{
        $("#txtAge").hide();
    } 
});
Mohammed Safeer
  • 20,751
  • 8
  • 75
  • 78
  • Please read [answer] and always remember that you are not merely solving the problem at hand, but also educating the OP and any future readers of this question and answer. Thus, please [edit] the answer to include an explanation as to why it works. – Adriaan Mar 22 '22 at 12:41
7

I'm using jQuery 1.11.1 and I had troubles with setting and reading checkbox value as well.

I finally solved it by these two functions:

function setCheckboxValue(checkBoxId, checked) {
    if (checkBoxId && (checked === true || checked === false)) {
        var elem = $('#' + checkBoxId);
        if (checked === true) {
            elem.attr('checked', 'checked');
        } else {
            elem.removeAttr('checked');
        }
    }
}

function isChecked(checkBoxId) {
    return $('#' + checkBoxId).attr('checked') != null;
}

It might looks a little bit dirty but it solves all the wired issue I had among different types of browsers.

Jacob
  • 3,598
  • 4
  • 35
  • 56
7

You Can Try This code:

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});
Praneeth Madush
  • 158
  • 2
  • 12
  • Please read [answer] and always remember that you are not merely solving the problem at hand, but also educating the OP and any future readers of this question and answer. Thus, please [edit] the answer to include an explanation as to why it works. – Adriaan Mar 22 '22 at 12:41
6
if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}
RevanthKrishnaKumar V.
  • 1,855
  • 1
  • 21
  • 34
user1996628
  • 21
  • 1
  • 1
  • Please read [answer] and always remember that you are not merely solving the problem at hand, but also educating the OP and any future readers of this question and answer. Thus, please [edit] the answer to include an explanation as to why it works. – Adriaan Mar 22 '22 at 12:41
5
$(document).on('change', '#isAgeSelected', function() {

    if($(this).is(":checked")){

       $('#txtAge').hide();
    }
    else
    {
        $('#txtAge').hide();
    }
});
Sanket Thakkar
  • 411
  • 3
  • 8
4

What about this solution?

$("#txtAge")[
    $("#isAgeSelected").is(':checked') ?
    'show' :
    'hide'
]();
Iter Ator
  • 8,226
  • 20
  • 73
  • 164
  • Please read [answer] and always remember that you are not merely solving the problem at hand, but also educating the OP and any future readers of this question and answer. Thus, please [edit] the answer to include an explanation as to why it works. – Adriaan Mar 22 '22 at 12:42
4

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

E.X -

1) Run On load to get checkbox value if the age checkbox is checked, then I need to show a text box to enter age, else hide the text box.

2) if the age checkbox is checked, then I need to show a text box to enter age, else hide the text box using click event of checkbox.

so code not returns false by default:

Try the following:

<html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        </head>
        <body>
            <h1>Jquery Demo</h1>
            <input type="checkbox" name="isAge" checked id="isAge"> isAge <br/>
            <div id="Age" style="display:none">
              <label>Enter your age</label>
              <input type="number" name="age">
            </div>
            <script type="text/javascript">
            if(document.getElementById('isAge').checked) {
                $('#Age').show();
            } else {
                $('#Age').hide();
            }   
            $('#isAge').click(function() {
                if(document.getElementById('isAge').checked) {
                    $('#Age').show();
                } else {
                    $('#Age').hide();
                }
            }); 
            </script>
        </body>
    </html>

Here is a modified version : https://jsfiddle.net/sedhal/0hygLtrz/7/

sedhal
  • 522
  • 4
  • 13
4

Hi you can use plain Javascript, like so:

document.getElementById('checkboxOption').addEventListener('click',      
   event => console.log(event.target.checked)
);
<label><input type="checkbox" id="checkboxOption">Check Option</label>
rcoro
  • 326
  • 6
  • 12
  • Please read [answer] and always remember that you are not merely solving the problem at hand, but also educating the OP and any future readers of this question and answer. Thus, please [edit] the answer to include an explanation as to why it works. – Adriaan Mar 22 '22 at 12:42
3

In case you need to know if a checkbox is checked in pure javascript you should use this code .

let checkbox =document.getElementById('myCheckboxId');
if(checkbox.checked) {
    alert("element is checked");
} else {
    alert("element is  ot checked");
}
4b0
  • 21,981
  • 30
  • 95
  • 142
Ir Calif
  • 460
  • 6
  • 7
3

In pure js checkbox state is easier to read

isAgeSelected.checked

function check() {
  txtAge.style.display= isAgeSelected.checked ? 'block':'none';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

<button onclick="check()">Check</button>

<div id="txtAge" style="display:none">
Age is selected
</div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
2
if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}
Abdul Hamid
  • 3,222
  • 3
  • 24
  • 31
2

For older versions of jQuery, I had to use following,

$('#change_plan').live('click', function() {
     var checked = $('#change_plan').attr('checked');
     if(checked) {
          //Code       
     }
     else {
          //Code       
     }
});
Vajira Lasantha
  • 2,435
  • 3
  • 23
  • 39
1

In case if you need to use CSS class as jQuery selector you can do following:

$(document).ready(function () {
        $('.myOptionCheckbox').change(function () {            
            if ($(this).prop('checked') == true) {
                console.log("checked");           
            }
            else {
                console.log("unchecked");                
            }
        });
    });

It works fine for checkboxes and radioboxes as well.

NoWar
  • 36,338
  • 80
  • 323
  • 498
1

This function is alternative and stable:

$('#isAgeSelected').context.checked
(return True/False)

Example:

if($('#isAgeSelected').context.checked){ //if Checkbox is checked then bla bla..
    /*.....*/
}else{
    /*.....*/
}
Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
Ferhat KOÇER
  • 3,890
  • 1
  • 26
  • 26
1
$('#chk').change(function() { 
    (this.checked)? alert('true') : alert('false');
});



($('#chk')[0].checked)? alert('true') : alert('false');
Leon Gaban
  • 36,509
  • 115
  • 332
  • 529
argie cruz
  • 223
  • 2
  • 8
0
if($('#isAgeSelected').prop('checked')) {
    // do your action 
}
Matt S
  • 14,976
  • 6
  • 57
  • 76
Vikash
  • 3,391
  • 2
  • 23
  • 39
0

You could try the followings in both ways:

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

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

if (getVal==true) {
 $("#txtAge").show();  // checked
} else {
 $("#txtAge").hide();  // unchecked
}
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
-1

$("#isAgeSelected").prop('checked', true);

Nad
  • 4,605
  • 11
  • 71
  • 160
Sudha
  • 159
  • 1
  • 2