根据现场输入计算总和

时间:2016-07-04 20:21:16

标签: jquery forms jquery-calculation

如何汇总多个文本输入的值?

目前总和不正确,因为它始终记住和汇总之前输入字段中的先前值。

我有以下代码:

HTML:

<div class="form-group">
  <legend>Risicopotentieel</legend>
  <label for="email">Email address:</label>
  <select class="selectpicker" id="selectpicker1">
    <option value="1">text1</option>
    <option value="2">text2</option>
    <option value="3">text3</option>
    <option value="4">text4</option>
  </select>
  <label for="email">Email address:</label>
  <select class="selectpicker" id="selectpicker2">
    <option value="1">text1</option>
    <option value="2">text2</option>
    <option value="3">text3</option>
    <option value="4">text4</option>
  </select>
  <label for="email">Email address:</label>
  <select class="selectpicker" id="selectpicker3">
    <option value="1">text1</option>
    <option value="2">text2</option>
    <option value="3">text3</option>
    <option value="4">text4</option>
  </select>
</div>

<div class="form-group">
  <legend>Score</legend>
  <label for="email">&nbsp;&nbsp;</label>
  <input type="text" class="form-control" id="scorefield1">
  <label for="email">&nbsp;&nbsp;</label>
  <input type="text" class="form-control" id="scorefield2">
  <label for="email">&nbsp;&nbsp;</label>
  <input type="text" class="form-control" id="scorefield3">
  <label for="email">Totaalscore</label>
  <input type="text" class="form-control" name="riskpottotalscore" id="riskpottotalscore">
</div>

jQuery代码首先将所选选项的值复制到输入字段。这很好用。此后,我想计算总和,那就是它出错了。变量 totalPoints 会记住它的分数,但我只想计算在分数字段1,2和3中实际选择的值的总和:

scorefieldrisk: function(){
    totalPoints = 0;
    for (var i = 1; i <= 7; i++) {
        (function (i) {
            $('select[id$="selectpicker' + i + '"]').on("change", function() {
                document.getElementById('scorefield'+i).value = this.value;
                if(!isNaN(this.value) && this.value.length!=0) {
                    totalPoints +=(parseInt(this.value));
                    document.getElementById('riskpottotalscore').value = totalPoints;
                }
            });
        })(i);
    }
},

1 个答案:

答案 0 :(得分:2)

你应该每次从零重做总和。

您的代码可以简化为只有一个函数作为所有select元素的处理程序。您还可以使用单一+运算符将字符串值转换为数字:

$('.selectpicker').on('change', function() {
    totalPoints = 0;
    $('.selectpicker').each(function() {
        totalPoints += +this.value;
    });
    $('#riskpottotalscore').val(totalPoints);
});