Javascript 如何从javascript更新输入文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2388629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:04:41  来源:igfitidea点击:

How to update an input text from javascript?

javascripttextboxbutton

提问by anand

I have this simple code that speaks for itself.Here it is:

我有这个不言自明的简单代码。它是:

<script language='javascript"> 
    function check() {} 
</script> 
<div id="a">input type="text" name="b"> 
<input type="button" onClick=" check(); ">

All i want is that when i press the button, the text field gets a value updated to it.

我想要的是,当我按下按钮时,文本字段会更新一个值。

I tried using b.value=" C " but it doesnt seem to work.

我尝试使用 b.value=" C " 但它似乎不起作用。

回答by Marcos Placona

<script language="javascript"> 
     function check() {
          document.getElementById('txtField').value='new value here'
     } 
</script>

<input id="txtField" type="text" name="b"> <input type="button" onClick=" check(); ">

This will do. I gave it an ID, and used getElementById('txtField') using the id, and updated it's value.

这会做。我给了它一个 ID,并使用该 ID 使用 getElementById('txtField'),并更新了它的值。

回答by Robusto

You seem to be thinking that giving a form input a name attribute makes it addressable as though it were a global variable. It doesn't. There is a syntax for that, and you would have to use something like:

您似乎在想,给表单输入一个 name 属性使其可寻址,就好像它是一个全局变量一样。它没有。有一个语法,你必须使用类似的东西:

document.forms[0].b.value = "C";

in order to get to address it successfully. You areputting your form elements inside a form, aren't you?

以便成功解决它。你把你的窗体元素里面,不是吗?

Do it that way, or use an ID along with the getElementById method, as mplacona suggests.

按照 mlacona 的建议,这样做,或者将 ID 与 getElementById 方法一起使用。