Check whether a checkbox is checked in jQuery

Today in this post we are going to see how to detect whether an HTML input checkbox is checked or not. We are going to see it with the simple example of code.

Below is the HTML code for the checkbox type input:

<input type="checkbox" id="mycheckbox">See what happens with the checkbox

In the above HTML code, you can see that we have set the id “mycheckbox” which will be used as the selector in jQuery to apply change() method so that we can detect the changes of the checkbox.

Show or hide input field based on checkbox using jQuery

You also need to include the jQuery file:

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

I have included the jQuery file from the official jQuery website. We are going to use jQuery method to do the task.

Now below is the jQuery code which will check if the checkbox is checked or not:

$( "#mycheckbox" ).change(function() {

    if($('#mycheckbox').prop('checked')) {
       alert('Checkbox is checked');
    } else {
       alert('Checkbox is not checked');
    }

});

In the above code, we have applied the jQuery change() method to the checkbox input field by selecting the id “mycheckbox”. After that, we have used jQuery prop() method to check whether the checkbox is checked or not. The prop() method of jQuery sets or returns properties and values of the selected elements. Here we have used this method.

Show or hide input field based on checkbox using jQuery

We have used if else condition to check if the checkbox is checked or not. To detect if it is working or not, we have set the alert message.

Now if we check the checkbox, it will alert a message “Checkbox is checked”. After that, if you uncheck the checkbox field, it will show the alert message “Checkbox is not checked”.

I hope, from this tutorial and the sample code in this post, you have understood how to detect if a checkbox is checked or not. Please comment below if you need any other thing related to this tutorial.

Leave a Reply

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