input累加求和,快折腾死小弟我了,大神救救小弟我啊
input累加求和,快折腾死我了,大神救救我啊!!!!
我在做的页面中,有这样一个情况,这个price[X]个数不确定,有时多有时少,现在要将这些input中的值进行累加求和,并显示在<input type="text" name="priceTotal" id="priceTotal">中。
<input type="text" name="price1" id="price1">
<input type="text" name="price2" id="price2">
<input type="text" name="price3" id="price3">
<input type="text" name="price4" id="price4">
……
我是这样写的,但不对:
function sum_total(){
var i=1;
i++;
{$("priceTotal").value =$("priceTotal").value+$("price"+i+"").value;}
}
各位帮我看看呢
谢谢!!!!!!
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
写错了。
------解决方案--------------------
unction sum_total(){
$('#priceTotal').val(0);
$('[name^=price]').each(function(){
$('#priceTotal').val(parseFloat($('#priceTotal').val()) + parseFloat($(this).val()));
});
}
我在做的页面中,有这样一个情况,这个price[X]个数不确定,有时多有时少,现在要将这些input中的值进行累加求和,并显示在<input type="text" name="priceTotal" id="priceTotal">中。
<input type="text" name="price1" id="price1">
<input type="text" name="price2" id="price2">
<input type="text" name="price3" id="price3">
<input type="text" name="price4" id="price4">
……
我是这样写的,但不对:
function sum_total(){
var i=1;
i++;
{$("priceTotal").value =$("priceTotal").value+$("price"+i+"").value;}
}
各位帮我看看呢
谢谢!!!!!!
js累加求和
------解决方案--------------------
function sum_total(){
var sum = 0;
$(":text[name^='price']").each(function(){
if($(this).val()){
sum += parseInt($(this).val());
}
});
$("priceTotal").value(sum);
}
------解决方案--------------------
<script type="text/javascript">
window.onload = function(){
document.getElementById('abv').onclick = function(){
var sum = 0;
for(var i = 1 ; i < 5 ; ++i){
sum += +document.getElementById('price'+i).value;
}
document.getElementById('priceTotal').value = sum;
}
}
</script>
<input type="text" name="priceTotal" id="priceTotal"/>
<input type="button" id="abv" value="测试用按钮"/>
<div id="div1">
<input type="text" name="price1" id="price1" />
<input type="text" name="price2" id="price2" />
<input type="text" name="price3" id="price3" />
<input type="text" name="price4" id="price4" />
</div>
------解决方案--------------------
写错了。
var total = 0,i=1;
function sum_total(){
var ele = document.getElementById("price"+i);
i++;
if(ele){
if(!isNaN(ele.value)){
total += Number(ele.value);
}
sum_total();
}
}
sum_total();
document.getElementById("priceTotal").value = total;
------解决方案--------------------
unction sum_total(){
$('#priceTotal').val(0);
$('[name^=price]').each(function(){
$('#priceTotal').val(parseFloat($('#priceTotal').val()) + parseFloat($(this).val()));
});
}