HTML DOM Input Search autofocus Property

HTMLWeb DevelopmentFront End Technology

The HTML DOM Input Search autofocus property is associated with the HTML <input> element’s autofocus attribute. This property is used for setting or returning if the input search field should automatically be focused when the page loads or not.

Syntax

Following is the syntax for −

Setting the autofocus property −

searchObject.autofocus = true|false

Here, true represents the search field should get focus and false represents otherwise. It is set to false by default.

Example

Let us look at an example of the Input search autofocus property −

<!DOCTYPE html>
<html>
<body>
<h1>Input search autofocus property</h1>
<form>
FRUITS: <input type="search" id="SEARCH1" name="fruits" autofocus>
</form>
<p>Get the autofocus attribute value for the above search field by clicking the below
button.</p>
<button type="button" onclick="FocusVal()">CHECK FOCUS</button>
<p id="Sample"></p>
<script>
   function FocusVal() {
      var R = document.getElementById("SEARCH1").autofocus;
      document.getElementById("Sample").innerHTML = "The search field has autofocus property
set to "+R;
}
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CHECK FOCUS button −

In the above example −

We have first created an <input> element with type=”search”, id=”SEARCH1”, name=”fruits” and it has its autofocus attribute set to true. The search field is inside a form −

<form>
FRUITS: <input type="search" id="SEARCH1" name="fruits" autofocus>
</form>

We then create a button CHECK FOCUS that will execute the FocusVal() method when clicked by the user −

<button type="button" onclick="FocusVal()">CHECK FOCUS</button>

The FocusVal() method gets the input element with type search using the getElementById() method and gets its autofocus property. The autofocus property returns true and false depending on the search field autofocus attribute value. This value is assigned to variable f and displayed in the paragraph with id “Sample” using its innerHTML property −

function FocusVal(){
   var f = document.getElementById("SEARCH1").autofocus;
   document.getElementById("Sample").innerHTML = "The search field autofocus property is set to: "+f;
}
raja
Published on 19-Aug-2019 12:20:21
Advertisements