Checkboxes are a crucial element in web development that allows users to make multiple selections from a set of options.
If you’re a web developer, you may have encountered a scenario where you need to check or uncheck checkboxes using JavaScript or jQuery.
In this tutorial, we’ll show you how to accomplish this task in both JavaScript and jQuery.
Table of Contents
JavaScript Check and Uncheck Checkbox
The easiest way to check or uncheck a checkbox using JavaScript is by using the checked property.
The checked property is a boolean attribute that indicates whether the checkbox is selected or not.
To check the checkbox, set the checked property to true, and to uncheck it, set the checked property to false.
Here’s an example:
<input type="checkbox" id="checkbox"> <script> const checkbox = document.getElementById("checkbox"); function check() { checkbox.checked = true; } function uncheck() { checkbox.checked = false; } </script> <button onclick="check()">Check</button> <button onclick="uncheck()">Uncheck</button>
In this example, we use the getElementById
method to select the checkbox with an ID of checkbox
.
Then, we create two functions, check
and uncheck
, that set the checked property to either true or false, respectively.
Finally, we attach the check
and uncheck
functions to two buttons with the onclick
event.
jQuery Check and Uncheck Checkbox
jQuery provides a convenient way to check or uncheck a checkbox using the prop
method.
The prop
method allows you to get or set properties of an element.
To check the checkbox, set the checked
property to true, and to uncheck it, set the checked
property to false.
Here’s an example:
<input type="checkbox" id="checkbox"> <script> $(document).ready(function() { $("#check").click(function() { $("#checkbox").prop("checked", true); }); $("#uncheck").click(function() { $("#checkbox").prop("checked", false); }); }); </script> <button id="check">Check</button> <button id="uncheck">Uncheck</button>
In this example, we use the $(document).ready
method to ensure that the DOM is fully loaded before we start manipulating the checkbox.
Then, we use the $("#check").click
and $("#uncheck").click
methods to attach the check
and uncheck
functions to two buttons with the ID of check
and uncheck
, respectively.
Finally, we use the $("#checkbox").prop("checked", true)
and $("#checkbox").prop("checked", false)
methods to check or uncheck the checkbox with an ID of checkbox
.
Conclusion
Checking and unchecking checkboxes with JavaScript and jQuery is a simple task that can be accomplished with just a few lines of code.
Whether you’re using JavaScript or jQuery, you can use the checked
property or the prop
method to check or uncheck a checked box.