简体   繁体   English

如何使用javascript更改HTML文本字段的值

[英]how to change value of textfield of HTML using javascript

<head>
<script type="javascript">
function display()
    {
        document.getElementById("textField1").value = "abc";
    }
</script>
</head>
<body>

<form id="form1" action="http://google.com">

<input id="textField1" type="text" value="0" align="right" size="13"/><br>

<input id="button1" type="button" value="1" onclick="display()">
</form>
</body>

but the value of textfield is not changing. 但是textfield的值并没有改变。

Any Ideas what am i doing wrong ?? 任何想法我做错了什么?

try 尝试

<script type="text/javascript">

instead of 代替

<script type="javascript">

. I believe the latter is not a valid syntax. 我相信后者不是一个有效的语法。

Removing the type attribute entirely works as well: 删除type属性也完全有效:

<script>

Remove the type from your script tag. script标记中删除type It's incorrect and making the browser not treat the script contents as JavaScript. 这是不正确的,并使浏览器不将script内容视为JavaScript。 Here it is not working , and here it is working (with the type="javascript" removed). 这里它不起作用这里它正在工作 (删除了type="javascript" )。

Your line 你的路线

document.getElementById("textField1").value = "abc";

is correct, try 是的,试试吧

    <head>
<script>
function display() {
        document.getElementById("textField1").value = "abc";
    }
</script>
</head>
<body>

<form id="form1" action="http://google.com">

<input id="textField1" type="text" size="13" value="clear" /><br>

<input type="button" onclick="display()">
</form>
</body>

It has to be 它一定要是

<script type="text/javascript">
function display()
    {
        document.getElementById("textField1").value = "abc";
    }
</script>

and not 并不是

<script type="javascript">
function display()
    {
        document.getElementById("textField1").value = "abc";
    }
</script>

In case the text field is not having id attribute and having name attribute then, 如果文本字段没有id属性并且具有name属性,那么,

use 采用

 document.getElementsByName("name")[0].value="ert"; 

getElementsByName() returns an array of objects with that specific name,that's why we are using the index 0. getElementsByName()返回具有该特定名称的对象数组,这就是我们使用索引0的原因。

There is nothing wrong with your code, it works fine in this fiddle . 您的代码没有任何问题,它可以在这个小提琴中正常工作。

I only speculate, but you could try to either delete the type attribute of the script-tag, or change it to type="text/javascript" which would be the proper type to use. 我只推测,但您可以尝试删除脚本标记的type属性,或将其更改为type="text/javascript" ,这将是正确使用的类型。 If you don't specify it, the browser will consider it as JavaScript by default. 如果您不指定它,浏览器会默认将其视为JavaScript。

它实际上是正确的,但如果它不起作用,请尝试这样:

document.getElementById("textfield1").innerHtml = "ABC";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM