checkbox is checked jquery

Using the jQuery prop() Method

The jQuery prop() method provides a simple, effective, and reliable way to track down the current status of a checkbox. It works pretty well in all conditions because every checkbox has a checked property which specifies its checked or unchecked status.

Do not misunderstand it with the checked attribute. The checked attribute only define the initial state of a checkbox, and not the current state. Let’s see how it works:

<script>
    $(document).ready(function(){
        $('input[type="checkbox"]').click(function(){
            if($(this).prop("checked") == true){
                console.log("Checkbox is checked.");
            }
            else if($(this).prop("checked") == false){
                console.log("Checkbox is unchecked.");
            }
        });
    });
</script>

Using the jQuery :checked Selector

You can also use the jQuery :checked selector to check the status of checkboxes. The :checked selector specifically designed for radio button and checkboxes.

Let’s take a look at the following example to understand how it basically works:

<script>
    $(document).ready(function(){
        $('input[type="checkbox"]').click(function(){
            if($(this).is(":checked")){
                console.log("Checkbox is checked.");
            }
            else if($(this).is(":not(:checked)")){
                console.log("Checkbox is unchecked.");
            }
        });
    });
</script>

Leave a Reply