Prasad
Prasad

Reputation: 59521

How do I check whether a checkbox is checked in jQuery?

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?

Upvotes: 5222

Views: 4934631

Answers (30)

Du-Lacoste
Du-Lacoste

Reputation: 12787

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
}

Upvotes: 5

Sanket Thakkar
Sanket Thakkar

Reputation: 231

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

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

       $('#txtAge').hide();
    }
    else
    {
        $('#txtAge').hide();
    }
});

Upvotes: 6

Bhanu Krishnan
Bhanu Krishnan

Reputation: 3726

Use jQuery's is() function:

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

Upvotes: 2290

Rajesh Omanakuttan
Rajesh Omanakuttan

Reputation: 6918

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();
}

Upvotes: 112

Ajay Katariya
Ajay Katariya

Reputation: 459

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>

Upvotes: 73

Dan Walters
Dan Walters

Reputation: 1376

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.

Upvotes: 29

Sarvesh Patel
Sarvesh Patel

Reputation: 133

$(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>

Upvotes: 15

rcoro
rcoro

Reputation: 326

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>

Upvotes: 5

Sandeep Sherpur
Sandeep Sherpur

Reputation: 2802

This code will help you

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});

Upvotes: 60

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92627

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>

Upvotes: 4

Javed Khan
Javed Khan

Reputation: 395

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
    }

   });

});

Upvotes: 23

Praneeth Madush
Praneeth Madush

Reputation: 158

You Can Try This code:

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});

Upvotes: 7

Udit Bhardwaj
Udit Bhardwaj

Reputation: 1781

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.

Upvotes: 76

Abraham
Abraham

Reputation: 9885

Using pure JavaScript:

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

if(checkbox.checked) {
  alert('is checked');
} else {
  alert('not checked yet');
}

Upvotes: 14

sedhal
sedhal

Reputation: 520

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/

Upvotes: 4

Ir Calif
Ir Calif

Reputation: 478

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");
}

Upvotes: 3

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 743

Simply use it like below

 $('#isAgeSelected').change(function() {
     if ($(this).is(":checked")) { // or if($("#isAgeSelected").attr('checked') == true){
         $('#txtAge').show();
     } else {
         $('#txtAge').hide();
     }
 });

Upvotes: 13

Lalji Dhameliya
Lalji Dhameliya

Reputation: 1769

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

Upvotes: 180

karim79
karim79

Reputation: 342715

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>

Upvotes: 3678

Jacob
Jacob

Reputation: 3698

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.

Upvotes: 7

Hamid N K
Hamid N K

Reputation: 87

Use this:

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

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

Upvotes: 44

Sangeet Shah
Sangeet Shah

Reputation: 3097

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>

Upvotes: 50

Ormoz
Ormoz

Reputation: 3013

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.

Upvotes: 28

zamoldar
zamoldar

Reputation: 598

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;

Upvotes: 8

Parth Chavda
Parth Chavda

Reputation: 1829

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:

Upvotes: 54

ungalcrys
ungalcrys

Reputation: 5620

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.

Upvotes: 276

Khaled.K
Khaled.K

Reputation: 5960

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);
}

Upvotes: 15

Tsonev
Tsonev

Reputation: 435

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')

Upvotes: 20

Somnath Kharat
Somnath Kharat

Reputation: 3610

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"

Upvotes: 32

subham.saha1004
subham.saha1004

Reputation: 842

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')

Upvotes: 15

Related Questions