How to Uncheck a Checkbox Using JavaScript

In this tutorial, you will learn how to uncheck a checkbox using javascript. Checkboxes are used to provide limited number of options to a user. As a result, a user can select one or more options.

If there are multiple possible correct answers to a certain question, then checkboxes should be used. You must have experienced such a scenario in an exam where an objective question can have multiple correct answers.

Generally, checkboxes are left unchecked on the initial page load, but only in certain situations where the answer is predetermined, some of the checkboxes are left checked.

In HTML, a checkbox is created using an input element. Since it is a checkbox, we have access to the checked property.  This property returns a Boolean value depending upon the status of the checkbox.  Also, it can be used to check or uncheck the checkbox.

In the following example, we are going to uncheck a checkbox dynamically upon button click. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 4 elements in the HTML file (div, input, label, and button). The div element with a class of container is just a wrapper for the rest of the elements.
  • The innerText for the button element is “Uncheck”.
  • The input element is of type checkbox and it has a label of “I like Javascript”. It is checked by default and we are going to uncheck it with the help of javascript.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!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">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>

<body>

  <div class="container">
    <button>Uncheck</button>
    <div>
      <input type="checkbox" id="coding" value="javascript" checked>
      <label for="coding">I like Javascript</label>
    </div>
  </div>

  <script src="script.js"></script>
</body>

</html>
.container {
    width: 400px;
    margin: auto;
    display: flex;
    flex-direction: column;
}

button, input  {
  padding: 5px 10px;
  margin-bottom: 20px;
}

Javascript

  • We have selected the input element and the button element using the document.querySelector() method and stored them in checkbox and btn variables respectively.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are using the checked property of the input element and setting it to false. This will change the status of checkbox from checked to unchecked.
let checkbox = document.querySelector("input[type='checkbox']");
let btn = document.querySelector("button");

btn.addEventListener("click", () => {
  checkbox.checked = false
});