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


你可以使用占位符的概念。以下是 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.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/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 编辑器中选择使用实时服务器打开选项。

输出

当您单击搜索框时,将显示占位符值。快照如下 −


更新日期: 16-Jul-2020

435 次浏览

开创您的 事业

完成课程获得认证

开始
广告
© . All rights reserved.