Adding default search text to search box in HTML with JavaScript?

You can use the concept of placeholder. Following is the JavaScript code −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
<input type="text" id="textSearch" placeholder="Search the value" />
   var yourText= "John";
   var textBoxSearch = document.getElementById("textSearch");
   textBoxSearch.value = yourText;
   textBoxSearch.onfocus = function() {
      if (this.value == yourText) {
         this.value = '';

To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS Code editor.


When you click on the search box, the placeholder value will be visible. The snapshot is as follows −

Updated on: 16-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started