使用JavaScript从输入中读取数字始终返回NaN [英] Reading numbers from inputs with JavaScript always returns NaN

查看:170
本文介绍了使用JavaScript从输入中读取数字始终返回NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个简单地将2个字段相加的计算器。但无论我尝试什么它都行不通。如果我使用parseInt(),它也会返回NaN。

I want to create a calculator which simply sums 2 fields up. But whatever I try it does not work. It also returns "NaN", also if I use parseInt().

这是代码:

 <script type="text/javascript" language="Javascript">
 function doSum() 
 {
 var a = document.getElementsByName("a").value;
 var b = document.getElementsByName("b").value;

 var sum =  a + b;

 document.getElementById("sum").value = sum;
}
</script>

<form action="" method="POST">
<br/>a:<br/>
<input type="text" name="a" onblur='doSum()' value="0" size="5" />
<br/>b:<br/>
<input type="text" name="b" onblur='doSum()' value="0" size="5" />
<br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>

对不起那个菜鸟问题,但是我做错了什么?
感谢您的帮助!

Sorry for that noob question, but what I'am doing wrong? Thanks for any help!

推荐答案

提供 id s输入并使用 document.getElementById 唯一地识别它们。然后,使用<$ href =https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt,使用 parseInt 获取其十进制int值=noreferrer>基数参数设置为10并显示当前的结果。

Give ids to your inputs and identify them uniquely using document.getElementById. Then, obtain their decimal int values using parseInt with the radix parameter set to 10 and display the result as you currently do.

<script type="text/javascript" language="Javascript">
 function doSum() 
 {
  var a = parseInt(document.getElementById("a").value, 10);
  var b = parseInt(document.getElementById("b").value, 10);

  var sum =  a + b;

  document.getElementById("sum").value = sum;
}
</script>

<form action="" method="POST">
 <br/>a:<br/>
<input type="text" id="a" onblur='doSum()' value="0" size="5" />
 <br/>b:<br/>
<input type="text" id="b" onblur='doSum()' value="0" size="5" />
 <br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>

getElementsByName 返回元素列表和你即使列表只包含一个元素,也必须通过索引引用你想要的那个。

getElementsByName returns a list of elements and you'd have to refer to the one you want through an index, even if the list contains only one element.

getElementById 另一方面,通过其id返回唯一标识的元素。

getElementById on the other hand, returns an uniquely identified element, by its id.

这篇关于使用JavaScript从输入中读取数字始终返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆