auto calculate the sum of input values with javasc

2019-06-02 04:12发布

I've an html page which has many dynamically created input boxes. The number of text boxes vary each time. I want to calculate the sum of the numbers the user has entered, and disply it. When the user delete one number the sum should auto calculate.

How can i do it with javascript? Thanks

2条回答
倾城 Initia
2楼-- · 2019-06-02 05:01

In jQuery something like this should work with a few assumptions:

$('.toAdd').live('change', function() {
  var total = 0;

  $('.toAdd').each(function () {
    total += $(this).val();
  });

  $('#total').val(total);
});

The assumptions being that your input fields all have the class 'toAdd' and that your final input field has an ID of 'total'.

In pure JS:

var elems = document.getElementsByClassName('toAdd');

var myLength = elems.length,
total = 0;

for (var i = 0; i < myLength; ++i) {
  total += elems[i].value;
}

document.getElementById('total').value = total;
查看更多
甜甜的少女心
3楼-- · 2019-06-02 05:07

Let me elaborate when I review my notes but here is a high level answer that I believe will work... (My Java Script is very rusty)...

Make the input boxes share an attribute (or use tag) so you can get a collection to walk through no matter the size... Then on the onkeyup event on every input call this function that will sum the totals. Put the result into another entry with the ID you know beforehand...

You will have to validate input because if one of them is not a number then the total will also be "NAN"

Okay here is a complete working example you can build off of that I just threw together: It obviously needs a great deal of polishing on your end...

<html>
<head>
<script language="javascript">
function AddInputs()
{
    var total = 0;
    var coll = document.getElementsByTagName("input")
    for ( var i = 0; i<coll.length; i++)
    {
        var ele = coll[i];
        total += parseInt(ele.value);
    }
    var Display = document.getElementById("Display");
    Display.innerHTML = total;
}
</script>
</head>
<body>
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<span id="Display"></span>
</body>
</html>
查看更多
登录 后发表回答