通过单击按钮在 Javascript 中填充文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13979569/
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
Populate text box in Javascript by clicking on button
提问by GRicks
I am trying to populate a text box on a form by clicking on form buttons. Below is code I have so far - modified this code from a select box example -
我试图通过单击表单按钮来填充表单上的文本框。以下是我到目前为止的代码 - 从选择框示例中修改了此代码 -
<!DOCTYPE html>
<html>
<head>
<script>
function moveNumbers(){
var no=document.getElementById("no");
var txt=document.getElementById("result").value;
txt=txt + option;
document.getElementById("result").value=txt;
}
</script>
</head>
<body>
<form>
Select numbers:<br>
<input type="button" value="1" name="no" onclick="moveNumbers()">
<input type="button" value="2" name="no" onclick="moveNumbers()">
<input type="button" value="3" name="no" onclick="moveNumbers()">
<input type="text" id="result" size="20">
</form>
</body>
</html>
回答by Nick Rolando
There are a few flaws here. It doesn't seem like optionis defined. And you have no way to retrieve the button that was actually clicked.
这里有一些缺陷。好像没有option定义。而且您无法检索实际单击的按钮。
What you can do is pass this.valueto your onclick event handler. This passes the value of the button you push, and use that to append to your textbox value.
您可以做的是传递this.value给您的 onclick 事件处理程序。这会传递您按下的按钮的值,并使用它附加到您的文本框值。
<script> function moveNumbers(num) {
var txt=document.getElementById("result").value;
txt=txt + num;
document.getElementById("result").value=txt;
}
</script>
Select numbers: <br> <input type="button" value="1" name="no" onclick="moveNumbers(this.value)">
<input type="button" value="2" name="no" onclick="moveNumbers(this.value)">
<input type="button" value="3" name="no" onclick="moveNumbers(this.value)">
<input type="text" id="result" size="20">
回答by Tim Booker
Assuming you want the value of the button to be inserted into the text box:
假设您希望将按钮的值插入到文本框中:
<!DOCTYPE html>
<html>
<head>
<script>
function moveNumbers(number){
document.getElementById("result").value=number;
}
</script>
</head>
<body>
<form>
Select numbers:<br>
<input type="button" value="1" name="no" onclick="moveNumbers(this.value)">
<input type="button" value="2" name="no" onclick="moveNumbers(this.value)">
<input type="button" value="3" name="no" onclick="moveNumbers(this.value)">
<input type="text" id="result" size="20">
</form>
</body>
</html>

