Computer >> Computer tutorials >  >> Programming >> Javascript

Program to check/uncheck checkboxes using JavaScript


Following is the code to check/uncheck checkboxes using JavaScript −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>Check/uncheck boxes using JavaScript</h1>
<input class="check" type="checkbox" />
<button class="Btn">Toggle</button>
<script>
   let BtnEle = document.querySelector(".Btn");
   let checkEle = document.querySelector(".check");
   BtnEle.addEventListener("click", () => {
      if (checkEle.checked === true) checkEle.checked = false;
      else checkEle.checked = true;
   });
</script>
</body>
</html>

Output

Program to check/uncheck checkboxes using JavaScript

On clicking the toggle button, the checkbox will be toggled −

Program to check/uncheck checkboxes using JavaScript