Search

jQuery Test if checkbox is NOT checked

post-title

JQuery is simple but very helpful and useful framework in web develoing. Every web developer should have known jQuery after learning Javascript. It saves lot a time to write lengthy code than Javascript.

In this article, we will learn on how to find if the clicked checkbox is checked or unchecked using JQuery.

jQuery has prop() method that sets or returns properties or property value. To return the property value in jQuery, use the bellow code:

$(selector).prop(property);

This way we can check if checkboc has checked property or not using bellow code.

$('input[type="checkbox"]').click(function() {
    if($(this).prop("checked") == true) {
        alert("you just checked checkbox.");
    } else if($(this).prop("checked") == false) {
        alert("you just unchecked checkbox.");
    }
});

Here is the full HTML code by which you can also test it. Just copy and paste bellow code in HTML file and run in the browser.

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>Get Checkbox checked property value</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-8 offset-md-2">
                    <h1>Get Checkbox checked property value</h1>
                    <div class="form-check">
                        <label class="form-check-label">
                            <input type="checkbox" class="form-check-input" value="checkbox-value">Check me!
                        </label>
                    </div>
                </div>
            </div>
        </div>
        <script type="text/javascript">
            $(document).ready(function() {
                $('input[type="checkbox"]').click(function() {
                    if($(this).prop("checked") == true) {
                        alert("you just checked checkbox.");
                    } else if($(this).prop("checked") == false) {
                        alert("you just unchecked checkbox.");
                    }
                });
            });
        </script>
    </body>
</html>

On check event, you can find checkbox value and set new event as you required. For example, I have set alert() event on checkbox.

I hope this article will help you.