如何读/写<输入>使用 JavaScript 在 HTML 文档中获取值?输入>
我的文档中有一个 。我希望用户进行一些输入。
var myVar = document.getElementById('userInput').value;
然后我希望这个值显示在另一个 中。
document.getElementById('Preview').value = myVar;
这段代码不知何故不起作用。
有人可以帮忙吗?
提前致谢!
I have an <input>
in my document. There I want the user to do some input.
var myVar = document.getElementById('userInput').value;
Then I want this value to be shown in another <input>
.
document.getElementById('Preview').value = myVar;
This code somehow doesn't work.
Can anybody help?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据之前评论中的更多信息进行更新:
提交按钮将提交表单,从而运行 JS 但立即清空表单。
(这可能仍然不是实际的问题,问题仍然缺少大部分代码)
在发现问题没有反映问题之前的原始答案:
var myVar
=
document.getElementById('userInput').value;
不要忘记
=
。(显然,您需要在事件处理程序中使用该代码,以便它不会仅在文档加载时和用户输入任何内容之前执行。)
Update based on further information in comments before:
Submit buttons will submit forms, thus running the JS but immediately blanking the form.
(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;
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.)
是形式吗?
尝试这样的事情:
Is it form?
Try something like this:
除了拼写错误之外,您还必须将事件处理程序绑定到第一个
:
Besides the typo, you have to bind an event handler to the first
<input>
: