Javascript Reference - HTML DOM Input Number required Property








The required property sets or gets whether a number field must be filled before submitting a form.

Browser Support

required Yes 10.0 Yes Yes Yes

Syntax

Return the required property.

var v = numberObject.required 

Set the required property.

numberObject.required=true|false


Property Values

Value Description
true|false Set whether a number field should be required field.
  • true - The number field is required
  • false - Default. The number field is not required




Return Value

A Boolean type value, true if the number field is a required part of form, otherwise false.

Example

The following code shows how to mark a number field as required.


<!DOCTYPE html>
<html>
<body>
<!--from   w ww  .ja v a  2  s .  co  m-->
<form action="url">
  Number: <input type="number" id="myNumber" name="quantity">
  <input type="submit">
</form>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("myNumber").required = true;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to check if a number field must be filled before submitting a form.


<!DOCTYPE html>
<html>
<body>
<!--   ww w  . j  a v  a 2s.com-->
<form action="url">
  Number: <input type="number" id="myNumber" name="quantity" required>
  <input type="submit">
</form>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
    var x = document.getElementById("myNumber").required;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows: