Jquery:求和输入文本字段

时间:2011-04-17 19:31:56

标签: javascript jquery input sum

我有一个包含输入文本字段的表格,其中包含以下基本结构。我无法构建一个函数来迭代表中的所有行,并且总结以BFObel开头的输入字段的所有值,其中以BFOkto开头的字段的值是相同的。因此,对于下面的基本示例,值1111的总和将为2000,值1112的总和将为3000.然后,每个总和将被写入具有id field1111,field1112等的输入字段...

<table>
  <tr id="BFOrow1">
    <td><input type="text" id="BFOtxt1" value="text"/></td>
    <td><input type="text" id="BFOkto1" value="1111" /></td>
    <td><input type="text" id="BFObel1" value="1000" /></td>
  </tr>
  <tr id="BFOrow2">
    <td><input type="text" id="BFOtxt2" value="text"/></td>
    <td><input type="text" id="BFOkto2" value="1111" /></td>
    <td><input type="text" id="BFObel2" value="1000" /></td>
  </tr>  
  <tr id="BFOrow3">
    <td><input type="text" id="BFOtxt3" value="text"/></td>
    <td><input type="text" id="BFOkto3" value="1112" /></td>
    <td><input type="text" id="BFObel3" value="1000" /></td>
  </tr>  
  <tr id="BFOrow4">
    <td><input type="text" id="BFOtxt4" value="text"/></td>
    <td><input type="text" id="BFOkto4" value="1112" /></td>
    <td><input type="text" id="BFObel4" value="1000" /></td>
  </tr>  
  <tr id="BFOrow5">
    <td><input type="text" id="BFOtxt5" value="text"/></td>
    <td><input type="text" id="BFOkto5" value="1112" /></td>
    <td><input type="text" id="BFObel5" value="1000" /></td>
  </tr>  
</table>

3 个答案:

答案 0 :(得分:2)

您需要使用对象文字来跟踪结果,并使用"attribute starts with" selector来查找文本输入:

var accumulator = { };
$('table input[id^=BFOkto]').each(function() {
    var sum_id = this.id.replace(/^BFOkto/, 'BFObel');
    if(!accumulator[this.value])
        accumulator[this.value] = 0;
    accumulator[this.value] += parseInt($('#' + sum_id).val(), 10);
});
// accumulator now has your results.

不要忘记parseInt()的第二个参数,这样就不会被带前导零的值绊倒(看起来像没有指定基数的八进制)。

例如:http://jsfiddle.net/ambiguous/QAqsQ/(您需要在带有开放式JavaScript控制台的浏览器中运行此功能,以查看生成的accumulator)。

答案 1 :(得分:0)

var sum1111 = 0;

$('input[value="1111"]').each(function() {
  var ordinal = $(this).attr('id').replace('BFOkto', '');
  sum1111 += parseInt($('#BFObel' + ordinal).val());
});

最后,sum1111应该等于2000。

要重用,请将逻辑包装在函数中:

function getSum(BFOkto) {
    var sum = 0;
    var ordinal = null;

    $('input[value="' + BFOkto + '"]').each(function() {
      ordinal = $(this).attr('id').replace('BFOkto', '');
      sum += parseInt($('#BFObel' + ordinal).val());
    });

    return sum;
}

然后致电:

getSum('1111');
getSum('1112');

答案 2 :(得分:0)

另一种方法:找到前缀为BFOkto的所有输入字段,为每个输入字段找到前缀为BFObel的输入,共享相同的父级并累积其值

ref = $("table td input[id^=BFOkto]");

var sums = new Object();
ref.each(function(){
    val = parseInt($(this).closest('tr').find("td input[id^=BFObel]").val(), 10);
    property = 'i'+ this.value;
    sums[property] = (sums[property] || 0 ) + val;
});

alert(sums['i1111']);
alert(sums['i1112']);

sums将是一个具有属性的对象

i1111 = 2000
i1112 = 3000

尽管javascript允许,但最好不要对对象(关联数组)使用纯数字属性,因此i前缀

正在运行的示例如下: http://jsfiddle.net/TbSau/1/