javascript 单击按钮时更新文本框值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23798989/
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
Update textbox value when a button is clicked
提问by user3635102
Here is my problem, when i click the submit button, the textbox doesn't show any value Is there any mistakes, i am just a newbie Thank you very much
这是我的问题,当我单击提交按钮时,文本框没有显示任何值 有什么错误吗,我只是一个新手 非常感谢
<form id="form1" name="form1" method="post" >
<p>
<input type="submit" name="setValue" id="setValue" value="submit" onclick="setValue()"/>
</p>
<p>
<label>
<input type="text" name="bbb" id="bbb" />
</label>
</p>
</form>
<script type="text/javascript">
function setValue()
{
document.getElementById('bbb').value="new value here";
}
</script>
回答by adeneo
The first issue is that you're using the same name for the element as the function, so window.setValue
is not the function, but the submit button, and that's an error.
第一个问题是您对元素使用与 function 相同的名称,因此window.setValue
不是函数,而是提交按钮,这是一个错误。
The second issue is that when you hit the submitbutton, the form is submitted and the page reloads, that's why you wont see a value, you have to prevent the form from submitting.
第二个问题是,当您点击提交按钮时,表单被提交并重新加载页面,这就是为什么您看不到值的原因,您必须阻止表单提交。
You could do it with javascript, but the easiest would be to just use a regular button instead of the submit button.
您可以使用 javascript 来完成,但最简单的方法是使用常规按钮而不是提交按钮。
<form id="form1" name="form1" method="post">
<p>
<input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
</p>
<p>
<label>
<input type="text" name="bbb" id="bbb" />
</label>
</p>
</form>
<script type="text/javascript">
function setValue() {
document.getElementById('bbb').value = "new value here";
}
</script>
回答by Olioul Islam Rahi
I was typing the same answer what Adeneo just given, thank you Adeneo.
And user3635102, your <form>
was good, you can keep it as it was. Only you need to change <input type="submit">
to <input type="button">
. if you need to submit the form in future you can update your Javascript as follows which will submit form1:
我正在输入 Adeneo 刚刚给出的相同答案,谢谢 Adeneo。user3635102,你<form>
很好,你可以保持原样。只有您需要更改<input type="submit">
为<input type="button">
. 如果您以后需要提交表单,您可以按如下方式更新您的 Javascript,这将提交表单 1:
<script>
function setValue() {
document.getElementById('bbb').value = "new value here";
document.getElementById("form1").submit();
}
</script>