Javascript DOM HTML Input Text required Property get

Introduction

Find out if a text field must be filled out before submitting a form:

var x = document.getElementById("myText").required;

Click the button to find out if the text field must be filled out before submitting the form.

View in separate window

<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php">
  Name: <input type="text" id="myText" name="fname" required>
  <input type="submit">
</form>//  w  w w .j ava 2s.  c o  m
<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 required property sets or gets whether a text field must be filled out before submitting a form.

This property mirrors the HTML required attribute.

Value Description
true The text field is a required part of form submission
false Default. The text field is not a required part of form submission

The required property returns true if the text field is a required part of form submission, otherwise it returns false.




PreviousNext

Related