How to usethe onclick event in Javascript

  • We are creating a function checkAll in which we are setting checked true for all the checkboxes using the for loop.
  • When a button is clicked to check all the checkboxes the onclick event will occur and checkAll function will be called.
  • Another button is present which is the reset button by clicking that button it will reset the settings and it will set the checked property as a false value.

Example: In this example, we have implemented the above-explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        How to Check/Uncheck the
        checkbox using JavaScript ?
    </title>
</head>
 
<body>
    <h1 style="color:green;">
        w3wiki
    </h1>
 
    <h2>Check/Uncheck the checkbox using JavaScript</h2>
 
    <form>
        <div>
            <input type="button" onclick="checkAll()" value="CHECK ALL">
            <input type="reset" value="UNCHECK ALL">
        </div>
 
        <div>
            <label>
                <input type="checkbox" class="check3"> First
            </label>
        </div>
 
        <div>
            <label>
                <input type="checkbox" class="check3"> Second
            </label>
        </div>
 
        <div>
            <label>
                <input type="checkbox" class="check3"> Third
            </label>
        </div>
 
    </form>
 
    <script>
 
        // Create function of check/uncheck box
        function checkAll() {
 
            let inputs = document.querySelectorAll('.check3');
 
            for (let i = 0; i < inputs.length; i++) {
                inputs[i].checked = true;
            }
        }
 
 
    </script>
</body>
 
</html>


Output:

How to Check/Uncheck the checkbox using JavaScript ?

In this article, we will learn how to check/uncheck the checkbox using JavaScript. As we know checkboxes are used to choose more than one value at a time so we can create a function to check more than one checkbox at a time.

We can check/uncheck the checkbox in two ways:

Table of Content

  • Using the onclick event
  • Using the window.addEventListener and window.onload functions

Similar Reads

Approach 1: Using the onclick event

We are creating a function checkAll in which we are setting checked true for all the checkboxes using the for loop. When a button is clicked to check all the checkboxes the onclick event will occur and checkAll function will be called. Another button is present which is the reset button by clicking that button it will reset the settings and it will set the checked property as a false value....

Approach 2: Using the window.addEventListener and window.onload functions

...