admin管理员组文章数量:1315960
I have this very basic calculator:
<html>
<body>
<form name="form">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="text" name="res" />
<input type="button" value="+" onclick="form.res.value = form.num1.value + form.num2.value" />
</form>
</body>
</html>
But it treats form.num1.value
and form.num2.value
as string and because of it the result is the concatenation of these values instead of addition.
How to treat them as numbers?
I have this very basic calculator:
<html>
<body>
<form name="form">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="text" name="res" />
<input type="button" value="+" onclick="form.res.value = form.num1.value + form.num2.value" />
</form>
</body>
</html>
But it treats form.num1.value
and form.num2.value
as string and because of it the result is the concatenation of these values instead of addition.
How to treat them as numbers?
Share Improve this question asked Dec 6, 2013 at 12:59 BillieBillie 9,14612 gold badges42 silver badges71 bronze badges4 Answers
Reset to default 6Wrap each value in a parseInt(value, 10)
or parseFloat(value)
.
Shortest way is the unary plus operator, which converts to Number:
+form.num1.value + +form.num2.value
Note: it will return NaN
for mixed inputs like "10 potatoes". To avoid that, you can use parseInt
or parseFloat
.
Try to convert them to number like this:
onclick="Numberform.res.value = Number(form.num1.value) + Number(form.num2.value)"
Convert them to numbers with the +
operator or parseFloat
.
本文标签: javascriptHow to treat input field value as a numberStack Overflow
版权声明:本文标题:javascript - How to treat input field value as a number? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741984350a2408583.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论