如何使用 javascript 添加表单值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5074073/
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 ADD form values using javascript?
提问by Hymanson5
this is the code i came up with but all it does is this 1+1=11 i need it to do 1+1=2.
这是我想出的代码,但它所做的只是这个 1+1=11 我需要它来做 1+1=2。
<head>
<script type="text/javascript">
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.form1.quantity.value;
two = document.form1.price.value;
c = one + two
document.form1.total.value = (c);
}
function stopCalc(){
clearInterval(interval);
}
</script>
</head>
<body>
<form name="form1">
Quantity: <input name="quantity" id="quantity" size="10">Price: <input name="price" id="price" size="10"><br>
Total: <input name="total" size="10" readonly=true><br>
<input onclick="startCalc();" onmouseout="stopCalc()" type="button" value="Submit">
</form>
</body>
of course this is a really simple form, but you get the idea please help me tell what i'm doing wrong here
当然,这是一个非常简单的表格,但是您明白了请帮我告诉我我在这里做错了什么
回答by Paul Schreiber
You need to use parseInt()to convert the string to an integer.
您需要使用parseInt()将字符串转换为整数。
c = parseInt(one, 10) + parseInt(two, 10)
回答by Gaurav
use this
用这个
c = parseInt(one,10) + parseInt(two, 10);
回答by Chandu
You need to convert the price values to numeric.
您需要将价格值转换为数字。
use parseFloat for price since it can have decimal values.
使用 parseFloat 作为价格,因为它可以有十进制值。
use parseInt with the radix.
将 parseInt 与基数一起使用。
e,g:
例如:
function calc(){
one = parseInt(document.form1.quantity.value, 10);
two = parseFloat(document.form1.price.value);
c = one + two
document.form1.total.value = (c);
}
回答by Mic
You can use the +to convert a string to a number (integer or float)
您可以使用+将字符串转换为数字(整数或浮点数)
c = +one + +two;
回答by Kareem
You can use this
你可以用这个
one = document.form1.quantity.value/1;
two = document.form1.price.value/1;

