Javascript Reference - HTML DOM Input Text required Property








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

Browser Support

required Yes 10.0 Yes No Yes

Syntax

Return the required property.

var v = textObject.required 

Set the required property.

textObject.required=true|false

Property Values

Value Description
true|false Set whether a text field should be required for form submission.
  • true - The text field is required
  • false - Default. The text field is not required




Return Value

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

Example

The following code shows how to set a text field to be a required part of form submission.


<!DOCTYPE html>
<html>
<body>
<!--from  w  w w. j  a  v a2 s .com-->
<form action="url">
  Name: <input type="text" id="myText" name="fname">
  <input type="submit">
</form>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("myText").required = true;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

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


<!DOCTYPE html>
<html>
<body>
<!--   w w  w  .j  a  v a2 s  .  c  o  m-->
<form action="url">
  Name: <input type="text" id="myText" name="fname" required>
  <input type="submit">
</form>
<button onclick="myFunction()">test</button>

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

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

</body>
</html>

The code above is rendered as follows: