jQuery各部分中输入值的总和 [英] jQuery sum of input values in sections
问题描述
我试图在多个部分中查找输入值的总和.我已经将我的代码放在下面了.
I'm trying to find the sum of input values within multiple sections. I've put my code so far below.
HTML:
The 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>
jQuery:
$('.section').each(function(){
var totalPoints = 0;
$(this).find('input').each(function(){
totalPoints += $(this).val();
});
alert(totalPoints);
});
请注意,这是我实际使用的代码的简化版本.因此,我希望这能提醒2个值(每个部分的总和):8然后是6.相反,我只是得到所有值的字符串.因此,第一部分会向0143发出警报.
Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143.
有什么主意如何获得累计金额而不是字符串?
Any ideas how I get a cumulative sum instead of a string?
推荐答案
并期望是2(int)
不是.
一种非常快速(且不是完全正确)的解决方案是:
a very quick (and not fully correct) solution is :
$('.section').each(function(){
var totalPoints = 0;
$(this).find('input').each(function(){
totalPoints += parseInt($(this).val()); //<==== a catch in here !! read below
});
alert(totalPoints);
});
赶上?为什么?
answer: 如果不这样做,应该始终使用基数原因,前导零是八进制!
answer: You should always use radix cause if you dont , a leading zero is octal !
parseInt("010") //8 ( ff)
parseInt("010") //10 ( chrome)
parseInt("010",10) //10 ( ff)
parseInt("010",10) //10 ( chrome)
好吧....你明白了.供应基数!
well.... you get the idea. supply radix !
最终解决方案(使用.each( function(index, Element) )
)
$('.section').each(function(){
var totalPoints = 0;
$(this).find('input').each(function(i,n){
totalPoints += parseInt($(n).val(),10);
});
alert(totalPoints);
});
这篇关于jQuery各部分中输入值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!