How To Uncheck All Checkbox In Jquery

Checkboxes are a common element in web forms, allowing users to select multiple options from a list. However, there might be occasions when you need to uncheck all checkboxes on a page or a specific form with a single click, using jQuery. In this blog post, we will explore the process of unchecking all checkboxes in jQuery.

Prerequisites

Before diving into the code, ensure that you have the following:

  • jQuery library included in your project. You can either download it from the official jQuery website or use a CDN (Content Delivery Network).

Uncheck All Checkboxes Using jQuery

Let’s assume that you have a set of checkboxes on your web page and a button that triggers the unchecking of all checkboxes. The HTML code for the setup might look like this:

    <form>
        <input type="checkbox" class="my-checkbox" value="Option 1"> Option 1<br>
        <input type="checkbox" class="my-checkbox" value="Option 2"> Option 2<br>
        <input type="checkbox" class="my-checkbox" value="Option 3"> Option 3<br>
        <input type="checkbox" class="my-checkbox" value="Option 4"> Option 4<br>
        <button type="button" id="uncheck-all">Uncheck All Checkboxes</button>
    </form>
    

Now, let’s write jQuery code to uncheck all checkboxes with the class “my-checkbox” when the “Uncheck All Checkboxes” button is clicked:

    $(document).ready(function() {
        $('#uncheck-all').on('click', function() {
            $('.my-checkbox').prop('checked', false);
        });
    });
    

Explanation:

  • We wrap our code inside the $(document).ready() function to make sure the entire DOM is loaded before our script starts executing.
  • We use the $(‘#uncheck-all’) selector to target the button with the id “uncheck-all”.
  • Then, we attach a click event listener to the button using the .on() function.
  • Inside the event handler function, we use the $(‘.my-checkbox’) selector to target all checkboxes with the class “my-checkbox”.
  • Finally, we use the .prop() function to set the “checked” property of all the matched checkboxes to false, effectively unchecking them.

Conclusion

In this blog post, we learned how to uncheck all checkboxes in jQuery using the .prop() function. This method allows you to quickly and easily uncheck multiple checkboxes on a web page or within a specific form with just a few lines of code. Happy coding!