HTML DOM Input Checkbox required Property

HTMLWeb DevelopmentFront End Technology

The Input Checkbox required property determines whether Input Checkbox is compulsory to check or not.

Syntax

Following is the syntax −

  • Returning boolean value - true/false
inputCheckboxObject.required
  • Setting required to booleanValue
inputCheckboxObject.required = booleanValue

Boolean Values

Here, “booleanValue” can be the following −

booleanValueDetails
trueIt defines that it is compulsory to check the checkbox to submit form.
falseIt is the default value and checking is not compulsory.

Example

Let us see an example of Input Checkbox required property −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>Required Attribute of Checkbox</title>
</head>
<body>
<form id="Form">
<div>
Check me ! I am required: <input id="formCheckbox" type="checkbox" name="formCheckbox" required>
</div>
</form>
<button onclick="getRequiredStatus()">Check if form is submittable</button>
<div id="displayDiv"></div>
<script>
   function getRequiredStatus(){
      var requiredBool = document.getElementById("formCheckbox");
      var displayDiv = document.getElementById("displayDiv");
      if(requiredBool.required == false || (requiredBool.required == true && requiredBool.checked == true)){
         displayDiv.textContent = 'Required attribute of checkbox: '+requiredBool.required + ', form is submittable ';
      } else {
         displayDiv.textContent = 'Check the checkbox'+ ', current value of required attribute: '+requiredBool.required ;
      }
   }
</script>
</body>
</html>

Output

This will produce the following output −

Clicking ‘Check if form is submittable’ button with unchecked checkbox −

After clicking ‘Check if form is submittable’ button with checked checkbox −

raja
Published on 19-Jul-2019 08:21:00
Advertisements