通过Javascript向文本框添加默认值

时间:2016-08-11 20:54:19

标签: 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>

仅供参考:这只是一个示例页面。
请指导我这个。如果此帖子无关,请不要降级。请告诉我,我会将其删除。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

如果您想通过JavaScript更改值,则必须使用以下代码:

document.getElementById('txtfirstName').value = 'test';

您的案例中的问题是您正在使用JQuery,我无法在您的案例中看到jQuery源的集成。您必须决定是否要使用JavaScript或jQuery进行操作。

使用JavaScript,您不需要外部框架,但我更喜欢jQuery而不是JavaScript,因为它更强大。

这将是JavaScript中的完整示例(无需框架):

<!DOCTYPE html>
<html>
<head>
<script>
    document.getElementById('txtfirstName').value = 'test';

</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>

使用jQuery看起来像这样(第一行中框架的集成):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){

        $("#txtfirstName").text("Hello world!");

});
</script>

所以你可以看到jQuery更简单,它使用的代码比JavaScript少。

看到它在这个JsFiddle工作:https://jsfiddle.net/Anokrize/aemy4nea/

答案 1 :(得分:0)

您需要将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来封装加载函数,因此填充全局对象(窗口对象)的无关变量和函数。

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