HTML DOM Input Search required property


The HTML DOM input Search required property is associated with the required attribute of an <input> element. The required property is used for setting and returning if it is necessary to fill some search field or not before the form is submitted to the server. This allows the form to not submit if a search field with required attribute is left empty by the user.

Syntax

Following is the syntax for −

Setting the required property −

searchObject.required = true|false

Here, true represents that the search field must be filled while false represents its optional to fill the field before submitting the form.

Example

Let us look at an example for the input search required property −

Live Demo

<!DOCTYPE html>
<html>
<body>
<h1>Input search required property</h1>
<p>Check if the above field is mandatory to be filled or not by clicking the below
button</p>
<form action="/Sample_page.php">
FRUITS: <input type="search" id="SEARCH1" name="fruits" required>
<input type="submit">
</form>
<br>
<button onclick="checkReq()">CHECK</button>
<p id="Sample"></p>
<script>
   function checkReq() {
      var Req=document.getElementById("SEARCH1").required;
      if(Req==true)
         document.getElementById("Sample").innerHTML="The search field must be filled before submitting";
      else
         document.getElementById("Sample").innerHTML="The search field is optional and can be left blank by the user";
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CHECK button −

If the required property is set true and you click submit −

Updated on: 19-Feb-2021

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements