views:

231

answers:

2

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

+1  A: 

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;
g.d.d.c
There is DOJO using in this project. Is there any solution with dojo or normal javascript ?
coder247
@coder247 - I believe that should work in pure JS. I haven't ever used DOJO so I can't speak to it having a direct way. You'll probably want to encapsulate that in a function, then bind that to the onChange handler for each input field.
g.d.d.c
+1  A: 

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>
Dining Philanderer