Menu

Select only one checkbox from a group of checkboxes

Create a group of checkboxes and allow only one selection. Here is the sample code for of creating checkbox using simple HTML and JavaScript.


HTML code

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
  <script>
  var checkboxChecked;
  document.addEventListener('input',(e)=> {
    if(e.target.getAttribute('name')=="termsCondition") {
      if(checkboxChecked)
        checkboxChecked.checked=false;
      }
      e.target.checked=true;
      checkboxChecked=e.target;
  })
  </script>
</head>
<body>
  <p>Select only one checkbox from a group of checkboxes.</p>
  <input type="checkbox" name="termsCondition" value="1" /> 1
  <input type="checkbox" name="termsCondition" value="2" /> 2
  <input type="checkbox" name="termsCondition" value="3" /> 3
  <input type="checkbox" name="termsCondition" value="4" /> 4
</body>
</html>

Output



Learn JavaScript and HTML

No comments:

Post a Comment