如何对存储在文本框数组中的值求和

时间:2014-11-20 09:47:00

标签: javascript arrays dynamic sum

如何使用 javascript 对存储在文本框数组中的值进行求和,并将其显示在单独的<div id="hasil"></div>中。

谢谢大家。

这是我的javascript:

&#13;
&#13;
function tambah() {
    var sum = 0;
    var cost = document.getElementsByName('jumlah[]');
    for (var i = 0; i < cost.length; i++)
    {
        sum += parseFloat(cost[i].value);
    }
    document.getElementById('hasil').value = sum;
}
&#13;
<html>
    <body>
        <form id="hitung" name="hitung">
            <label>Jumlah</label> <br> 
            <span class="input-group-addon">Rp.</span>
            <input name="jumlah[]" type="text" class="form-control" onChange="tambah();" >
            <span class="input-group-addon">,00</span><br>
            <span class="input-group-addon">Rp.</span>
            <input name="jumlah[]" type="text" class="form-control" onChange="tambah();" >
            <span class="input-group-addon">,00</span><br>
            <span class="input-group-addon">Rp.</span>
            <input name="jumlah[]" type="text" class="form-control" onChange="tambah();" >
            <span class="input-group-addon">,00</span>
            <div id="hasil"></div>
        </form>
    </body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

似乎问题是由于设置了#hasil元素的值。 DIV元素没有value,因此您无法使用.value = sum;

相反,您可以尝试:

document.getElementById('hasil').innerHTML = sum;

Here is a working example

答案 1 :(得分:-1)

function tambah(){
      var taxtva1 = $("#1").val();
      var taxtva2 = $("#2").val();
      var taxtva3 = $("#3").val();
      var total = Number(taxtva1) + Number(taxtva2) + Number(taxtva3);
     ("#hasil").text(total);
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <html>
        <body>
            <form id="hitung" name="hitung">
    <label>Jumlah</label> <br> 
    <span class="input-group-addon">Rp.</span>
    <input name="sum" id="1" type="text" class="form-control" onChange="tambah();" >
    <span class="input-group-addon">,00</span><br>
    <span class="input-group-addon">Rp.</span>
    <input name="sum" id="2" type="text" class="form-control" onChange="tambah();" >
    <span class="input-group-addon">,00</span><br>
    <span class="input-group-addon">Rp.</span>
    <input name="sum" id="3" type="text" class="form-control" onChange="tambah();" >
    <span class="input-group-addon">,00</span>
    <div id="hasil"></div>
              </form>
          </body>
      </html>