jquery & javascript

jQuery: Let’s Check if a Checkbox is Checked or Not

Checking if a checkbox is checked or not with jQuery is extremely useful. You can show an additional form field, enable or disable a submit button, or show a message. It’s a pretty common thing to do. So let’s see how to determine the state of a checkbox, using jQuery.


In this example, we will show or hide a div depending if the checkbox is checked or not. That’s the most common use case scenario for this. Inside that div there might be a button, some text or additional fields that you want to show to the user if they tick the box.
Here is our HTML, the checkbox will be checked by default:

<input type="checkbox" id="yourCheckbox" checked="checked"> Do you want to check it?

<div id="myDiv">my div</div>

Answer 1: Determining the state of a checkbox using .prop

.prop() is a convenient way to determine the state of a checkbox. As it names implies, .prop() gets the property value for only the first element in the matched set. So we can simply look if the “checked” property returns true or false.

$('#yourCheckbox').change(function(){
  if($(this).prop("checked")) {
    $('#myDiv').show();
  } else {
    $('#myDiv').hide();
  }
});

jQuery documentation warns us about the difference between attributes and properties:

Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
– the documentation

Therefore, while .attr() could work, you should use .prop() here.

Answer 2: Using :checked

The second valid way to do what we want is to use the :checked selector available in jQuery, which works for radio buttons as well.

It’s very straightforward, as it matches all elements that are checked or selected.

$('#yourCheckbox').change(function(){
  if($(this).is(":checked")){
    $('#myDiv').show();
  } else if($(this).is(":not(:checked)")){
    $('#myDiv').hide();
  }
});

Which one you choose is entirely up to what you prefer.

jQuery: Let’s Check if a Checkbox is Checked or Not
4 (80.95%) 21 votes

3 replies

Trackbacks & Pingbacks

  1. […] provides a convenient method for removing uploaded files if a checkbox is checked. We will use and adapt it to delete file from S3 after the Model has been […]

  2. […] Related: jQuery: Let’s Check if a Checkbox is Checked or Not […]

Comments are closed.