How to check whether a checkbox is checked in jQuery

Last Updated on :February 26, 2024

One common use case for jQuery is to check whether a checkbox is checked or not. In this post , we will look into how to do that using jQuery.

Checking Whether a Checkbox is Checked

To check if a checkbox is checked using jQuery, you can use the prop() method.If the checkbox is checked, the method will return true, otherwise it will return false.

Here’s an example:


// jQuery
$(document).ready(function () {
  $("#buttonsubmit").click(function () {
    var msg = "";
    if ($("#checkbox1").prop('checked')) {
      msg += "checkbox1 checked.";
    }
    if (msg.length) {
      alert(msg);
    } else {
      alert("Please select one checkbox");
    }
  });
});

Alternatively, you can also use the is() method to check whether a checkbox is checked, like below


// jQuery
$(document).ready(function () {
  $("#buttonsubmit").click(function () {
    var msg = "";


    if ($("#checkbox2").is(':checked')) {
      msg += "checkbox2 checked.";
    }

    if (msg.length) {
      alert(msg);
    } else {
      alert("Please select one checkbox");
    }
  });
}); 

The is() method checks for a :checked CSS pseudo-class, which would be added to a checkbox if it’s checked. It returns true if the checkbox is checked.

For an array of checkboxes with the same name you can get the list of checked ones like below


// jQuery
$(document).ready(function () {
  $("#buttonsubmit").click(function () {
    var msg = "";   
    var checkboxValues = [];
    var checkboxgrp = $('input[name=itemgroup]:checked');
    checkboxgrp.each(function(index, elem) {
        checkboxValues.push($(elem).val());
    });
   
    if(checkboxValues.length > 0){
    msg += "Item Group checked: "+checkboxValues.join(', ');
    }

    if (msg.length) {
      alert(msg);
    } else {
      alert("Please select one checkbox");
    }
  });
});

A sample CodePen for this article can be found here.

Conclusion

In this post, we looked at how to check whether a checkbox is checked in jQuery. We used the prop() and is() method to get the value of the “checked” property.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *