HTML DOM Input Search defaultValue Property

HTMLWeb DevelopmentFront End Technology

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 ;
}
raja
Published on 19-Aug-2019 08:53:54
Advertisements