jQuery | How to Dynamically Check/ Uncheck Checkbox

The prop() method of jQuery is used to check or uncheck a checkbox.

We can have a button or method to trigger a dynamic change in the checkbox selected state.

Use of prop() method

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Check/ Uncheck Checkbox Dynamically</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

    <script>
        $(function () {
            $("#check-uncheck").on("click", function () {
                if ($("input:checkbox").prop("checked")) {
                    $("input:checkbox").prop("checked", false);
                } else {
                    $("input:checkbox").prop("checked", true);
                }
                // OR
                // $("input:checkbox").prop("checked",!$("input:checkbox").prop("checked"));   
            });
        });
    </script>
</head>

<body>

    <p>
        <input type="checkbox" name="myCheckbox"> check/ uncheck on toggle
    </p>
    <button id="check-uncheck">Toggle Checkbox</button>

</body>

</html>

 

Leave a Comment

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