Javascript Reference - HTML DOM Input Checkbox required Property








The required property sets or gets whether a checkbox must be checked before submitting the form.

Browser Support

required Yes 10.0 Yes Yes Yes

Syntax

Return the required property.


var v = checkboxObject.required 

Set the required property.

checkboxObject.required=true|false

Property Values

Value Description
true|false Set whether a checkbox should be checked before submitting the form
  • true - The checkbox must be checked before submitting a form
  • false - Default. The checkbox is not required




Return Value

A Boolean type value, true if the checkbox is required before submitting the form, otherwise it returns false.

Example

The following code shows how to set a checkbox to be a required for form submission.


<!DOCTYPE html>
<html>
<body>
<form action="url">
  Checkbox: <input type="checkbox" id="myCheck" name="test">
  <input type="submit">
</form><!--from w ww .j  ava  2  s.  c om-->
<button onclick="myFunction()">test</button>
<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("myCheck").required = true;
    document.getElementById("demo").innerHTML = "done";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to check if a checkbox is required before submitting a form.


<!DOCTYPE html>
<html>
<body>
<!--   ww w. j a va2s . c  o  m-->
<form action="url">
  Checkbox: <input type="checkbox" id="myCheck" name="test" required>
  <input type="submit">
</form>
<button onclick="myFunction()">test</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myCheck").required;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows: