javascript - 通过 Javascript 添加默认值到文本框

标签 javascript textbox

我正在尝试将值添加到文本框,但我不知道我在哪里犯了错误。你们能帮忙解决这个问题吗?我无法在 HTML 标记本身中添加默认值。

<html>
<head>
<script>
    $(document).ready(function() {
        $("#txtfirstName").val("Your First Name Here!"); 
        $("input[id='txtlastName']").val("Your Last Name Here!"); 
});
</script>
</head>
<body>


  First name:<br>
  <input type="text" name="firstname" id="txtfirstName" >
  <br>
  Last name:<br>
  <input type="text" name="lastname" id="txtlastName">

</body>
</html>

仅供引用:这只是一个示例页面。
请指导我。如果这篇文章不相关,请不要降级。只要告诉我,我就会删除它。

感谢您的帮助。

最佳答案

您需要将 JavaScript 封装在脚本标记中。以下代码可以实现您想要的功能:

<script   
    src="https://code.jquery.com/jquery-3.1.0.min.js"   
    integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="     
    crossorigin="anonymous"></script>


<script>
    $(document).ready(function() {
        $("#txtfirstName").val("Your First Name Here!");
        $("input[id='txtlastName']").val("Your Last Name Here!");
    });
</script>
<body>


  First name:<br>
  <input type="text" name="firstname" id="txtfirstName" />
  <br>
  Last name:<br>
  <input type="text" name="lastname" id="txtlastName" />


<p>Note that the form itself is not visible.</p>

<p>Also note that the default width of a text input field is 20 characters.</p>

</body>

此外,我还更改了 JQuery 查找其中一个输入的方式,因此您可以看到另一种执行方式。

编辑: 如果您想不使用 JQuery 来执行此操作,则以下内容将使用纯 JavaScript 执行此操作。它使用 IIFE封装load函数,让无关的变量和函数填充到全局对象(window对象)中。

<script>
  (function () {
    function init () {
      document.getElementById("txtfirstName").value = "Your First Name Here!"
      document.getElementById("txtlastName").value = "Your Last Name Here!"
    }
    window.onload = init;
  }())
</script>

关于javascript - 通过 Javascript 添加默认值到文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38905969/

相关文章:

javascript - 复选框通过 vb.net 激活 asp.net 中的文本框

c# - 仅接受数字值的文本框中仅接受一个 "."

javascript - 动态创建的元素上的事件绑定(bind)?

Web 辅助功能屏幕阅读器无法读取 JavaScript 弹出对话框

javascript - 单击时添加背景颜色

java - jsp中的自动完成文本框

c++ - 从 cpp 文件更改文本框

javascript - 如何在 Ngrx 9.x 中设置状态值?

具有可变内容的javascript正则表达式

javascript - 如何动态添加文本框而不丢失以前文本框的值?