javascript - Jquery:求和输入文本字段

标签 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>

最佳答案

您需要使用对象字面量来跟踪您的结果,并使用 "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)。

关于javascript - Jquery:求和输入文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5695901/

相关文章:

用作标志的 JavaScript 全局变量

javascript - 使用 Jquery 根据选定的下拉选项隐藏表单元素

jquery - 获取图像 slider 以自动播放

javascript jquery 如果将大于 0 的数字插入到框中,则检查复选框

c++ - fstream 的数据输入不正确

javascript - 使用 jqprint 使用 CSS 打印特定的 DIV

javascript - 条件渲染与 TabNavigator

javascript - 下划线组通过使用服务器数据

javascript - 动画底部边框(从左到右)

c - 程序在读取输入时停止