使用 JavaScript 在 HTML 中的搜索框中添加默认搜索文本?

javascriptweb developmentobject oriented programminghtml

您可以使用占位符的概念。以下是 JavaScript 代码 −

示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input type="text" id="textSearch" placeholder="Search the value" />
<script>
   var yourText= "John";
   var textBoxSearch = document.getElementById("textSearch");
   textBoxSearch.value = yourText;
   textBoxSearch.onfocus = function() {
      if (this.value == yourText) {
         this.value = '';
      }
   }
</script>
</body>
</html>

要运行上述程序,请保存文件名anyName.html(index.html),然后右键单击该文件,在 VS Code 编辑器中选择使用实时服务器打开选项。

输出

单击搜索框时,占位符值将可见。快照如下 −


相关文章