带有sum的jQuery选择器

jQuery selector with sum

本文关键字:选择器 jQuery sum 带有      更新时间:2024-03-01

我不知道我的问题的好标题,这就是我没有搜索的原因。

我的问题如下:

我有一个HTML代码,例如:

<input type="text" id="product_qty_1" value="12" />
<input type="text" id="product_qty_2" value="21" />
<input type="text" id="product_qty_3" value="45" />

我想通过jQuery对值求和,但这需要是自动的,因为我们不知道有多少inputs

我不知道如何使用选择器input[id*="product_qty_"]使其工作,并对值求和!

提前感谢!

var total=0;
$("input[type='text']").each(function() {
    total += parseInt(this.value, 10);
});

您可以使用jQuery的each循环:

var sum = 0;
$('input[id*="package_qty_"]').each(function() {
    sum += parseInt(this.value, 10);
});
alert(sum);