如何使用 JavaScript 在 HTML 文档中读取/写入 <input> 值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6059235/
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
How do read/write <input> values in an HTML document with JavaScript?
提问by チーズパン
I have an <input>
in my document. There I want the user to do some input.
我的<input>
文档中有一个。在那里我希望用户做一些输入。
var myVar = document.getElementById('userInput').value;
Then I want this value to be shown in another <input>
.
然后我希望这个值显示在另一个<input>
.
document.getElementById('Preview').value = myVar;
This code somehow doesn't work.
这段代码不知何故不起作用。
Can anybody help?
有人可以帮忙吗?
Thanks in advance!
提前致谢!
回答by Quentin
Update based on further information in comments before:
根据之前评论中的更多信息进行更新:
<button onClick="calculateThatObscenityDeleted()">"Save"</button >
Submit buttons will submit forms, thus running the JS but immediately blanking the form.
提交按钮将提交表单,从而运行 JS 但立即空白表单。
(That might still not be the actual issue, the question is still missing most of the code)
(那可能仍然不是实际问题,问题仍然缺少大部分代码)
Original answer before it was revealed that the question didn't reflect the problem:
之前的原始答案被揭示该问题并未反映问题:
var myVar
=
document.getElementById('userInput').value;
var myVar
=
document.getElementById('userInput').value;
Don't forget the =
.
不要忘记=
.
(And, obviously, you need to use that code in an event handler so it isn't executed only when the document loads and before the user has typed anything.)
(而且,很明显,您需要在事件处理程序中使用该代码,因此它不会仅在文档加载时和用户输入任何内容之前执行。)
回答by demas
Is it form? Try something like this:
是形式吗?尝试这样的事情:
oFormObject = document.forms['myform_id'];
oFormObject.elements["element_name"].value = 'Some Value';
回答by wong2
Besides the typo, you have to bind an event handler to the first <input>
:
除了打字错误之外,您还必须将事件处理程序绑定到第一个<input>
:
var input_a = document.getElementById('userInput');
var input_b = document.getElementById('Preview');
input_a.onkeyup = function(){
input_b.value = input_a.value;
}