Html 如何将文本框中的值保存到变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19889954/
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 can i save a value in the textbox to a variable
提问by user2969182
I want to store the value given in the text box in a variable. I am beginner to javascript. Please help me out. Here s my code.
我想将文本框中给出的值存储在一个变量中。我是 javascript 初学者。请帮帮我。这是我的代码。
<!DOCTYPE html>
<html>
<body>
Days of Journey: <input type="text" id="doj" name="daysofjourney">
<input type="button" value="submit" onclick="dayscounter()">
<script language="javascript" type="text/javascript">
var travel = document.getElementById("doj").value;
function dayscounter() {
var days;
for(days = 1; days <= travel; days++) {
document.write(days);
}
}
</script>
</body>
</html>
回答by Zim84
You nearly had it already...
你几乎已经拥有了...
function dayscounter() {
var travel = document.getElementById("doj").value;
var days;
for(days=1;days<=travel;days++)
{
document.write(days);
}
}
The problem was, that your first assignment of the variable travel is made as soon as the HTML code is loaded. The user can't have made an input yet at that time, thus the variable stays empty. If you include document.getElementById("doj").value
inside the function, you will get the value at that specific time you launch the function.
问题是,您在加载 HTML 代码后立即对变量 travel 进行了第一次分配。用户此时还不能进行输入,因此变量保持为空。如果document.getElementById("doj").value
在函数内部包含,您将在启动函数的特定时间获得值。
回答by Vicky Gonsalves
Just parse value to int
只需将值解析为 int
var travel = +(document.getElementById("doj").value;);
回答by Wenchao You
You can use 'value' attribute of an text input to set it's value like:
您可以使用文本输入的 'value' 属性来设置它的值,例如:
<input type="text" id="textid" value="value content" />
<input type="text" id="textid" value="value content" />
and you can do your function like this:
你可以像这样完成你的功能:
<script language="javascript" type="text/javascript">
function dayscounter()
{
var travel = document.getElementById("doj").value;
var days;
var result = "";
for (days = 1; days <= parseInt(travel); ++days)
{
document.getElementById("result").value += " " + days;
}
}
</script>
Days of Journey:
<input type="text" id="doj" name="daysofjourney" />
<input type="button" value="submit" onclick="dayscounter()" />
<p>
<input type="text" id="result" />
</p>