How To Toggle Checkbox In Jquery

Checkboxes are a common element in web forms that allow users to select multiple options. In this tutorial, we will learn how to toggle checkbox elements using jQuery. Toggling a checkbox means changing its state from checked to unchecked or vice versa.

Prerequisites

Before getting started, make sure you have included the jQuery library in your HTML file. You can include it using the following script tag:

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

HTML Setup

Let’s create a simple HTML form containing a few checkboxes:

<form id="myForm">
    <input type="checkbox" name="option" value="option1"> Option 1<br>
    <input type="checkbox" name="option" value="option2"> Option 2<br>
    <input type="checkbox" name="option" value="option3"> Option 3<br>
    <button type="button" id="toggleCheckboxes">Toggle Checkboxes</button>
</form>

jQuery Code

Now, we will write the jQuery code to toggle the checkboxes when the “Toggle Checkboxes” button is clicked:

$(document).ready(function() {
    $("#toggleCheckboxes").on("click", function() {
        $("input[type='checkbox']").each(function() {
            $(this).prop("checked", !$(this).prop("checked"));
        });
    });
});

Explanation

  • $(document).ready() ensures that your code will only run once the document is completely loaded.
  • $("#toggleCheckboxes").on("click", ...) binds a click event to the button with the ID “toggleCheckboxes”.
  • $("input[type='checkbox']") selects all the checkboxes in the document.
  • $(this).prop("checked", !$(this).prop("checked")) toggles the “checked” property of the current checkbox in the loop.

Conclusion

In this tutorial, we have learned how to toggle checkboxes using jQuery. You can now easily implement this functionality in your web applications to provide a better user experience. Happy coding!