HTML DOM Input Search defaultValue Property



The HTML DOM Input Search defaultValue property is used for setting or getting the defaultValue of a search field. The defaultValue of an element is the value assigned to the value attribute. The difference between value and defaultValue property is that the defaultValue property retains the original default value while the value property value change based on the user input in the search field.

Syntax

Following is the syntax to set the defaultValue property βˆ’

searchObject.defaultValue = value

Here, β€œvalue” is the search field default value.

Example

Let us look at an example for the Search defaultValue property βˆ’

Live Demo

<!DOCTYPE html>
<html>
<body>
<h1>Input Search defaultValue Property</h1>
<form>
FRUITS: <input type="search" id="SEARCH1" name="fruits" value="MANGO">
</form>
<p>Change the above search field default value by clicking on the CHANGE button</p>
<button type="button" onclick="changeDefault()">CHANGE</button>
<p id="Sample"></p>
<script>
   function changeDefault() {
      document.getElementById("SEARCH1").defaultValue="APPLE";
      var P=document.getElementById("SEARCH1").defaultValue;
      document.getElementById("Sample").innerHTML = "Default value has been changed from MANGO to "+P ;
   }
</script>
</body>
</html>

Output

This will produce the following output βˆ’

On clicking the CHANGE button βˆ’

In the above example βˆ’

We have first created an <input> element with type=”search”, id=”SEARCH1”, name=”fruits” and it has its value attribute set to β€œMANGO”. The search field is inside a form βˆ’

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

We then create a button CHANGE that will execute the changeDefault() method when clicked by the user βˆ’

<button type="button" onclick="changeDefault()">CHANGE</button>

The changeDefault() method uses the getElementById() method to get the input field with type search and sets its defaultValue property to β€œAPPLE”. We then get the defaultValue property of the input with type search by again using the getElementById() method and assigning it to variable P. This variable is then displayed in the paragraph with id β€œSample” using the innerHTML property of the paragraph βˆ’

function changeDefault() {
   document.getElementById("SEARCH1").defaultValue="APPLE";
   var P=document.getElementById("SEARCH1").defaultValue;
   document.getElementById("Sample").innerHTML = "Default value has been changed from MANGO to "+P ;
}
Updated on: 2021-02-19T06:16:45+05:30

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements