jQuery部分中的输入值总和

Coo*_*oop 19 jquery input

我试图在多个部分中找到输入值的总和.我把我的代码放到了下面.

HTML:

<div class="section">
  <input type="radio" name="q1" value="2"/>
  <input type="radio" name="q2" value="0"/>
  <input type="radio" name="q3" value="1"/>
  <input type="radio" name="q4" value="3"/>
</div>
Run Code Online (Sandbox Code Playgroud)

jQuery:

$('.section').each(function(){
  var totalPoints = 0;
  $(this).find('input').each(function(){
    totalPoints += $(this).val();
  });
  alert(totalPoints);
});
Run Code Online (Sandbox Code Playgroud)

请注意,这是我实际使用的代码的简化版本.所以我希望这可以提醒2个值(每个部分的总和):8然后6.相反,我只是获取所有值的字符串.所以第一部分警告0143.

有什么想法我如何获得累积总和而不是字符串?

Roy*_*mir 35

你正在做"1"+"1"并期望它是2(int)

它不是.

一个非常快速(而且完全正确)的解决方案是:

$('.section').each(function(){
  var totalPoints = 0;
  $(this).find('input').each(function(){
    totalPoints += parseInt($(this).val()); //<==== a catch  in here !! read below
  });
  alert(totalPoints);
});
Run Code Online (Sandbox Code Playgroud)

赶上?为什么?

回答:如果你不这样做,你应该总是使用基数原因,前导零是八进制!

 parseInt("010") //8 ( ff)
 parseInt("010") //10 ( chrome)


 parseInt("010",10) //10 ( ff)
 parseInt("010",10) //10 ( chrome)
Run Code Online (Sandbox Code Playgroud)

反正你懂这个意思.供应基数!

编辑

最终解决方案(使用.each( function(index, Element) ))

$('.section').each(function(){
      var totalPoints = 0;
      $(this).find('input').each(function(i,n){
        totalPoints += parseInt($(n).val(),10); 
      });
      alert(totalPoints);
    });
Run Code Online (Sandbox Code Playgroud)

  • 稍微有趣的是你对需要指定基数提出了很大的意义,但实际上并没有在他的代码的更新版本中这样做. (3认同)
  • 这个答案现在令人困惑,无益. (2认同)

小智 6

使用parseFloat()parseInt()

var totalPoints = 0;
$('.section input').each(function(){
        totalPoints = parseFloat($(this).val()) + totalPoints;
});
alert(totalPoints);
Run Code Online (Sandbox Code Playgroud)