views:

3161

answers:

3

Hi everyone, im looking for some Javascript code to calculate the sum off multiple HTML-input values. The amount off inputs are dynamic so i'm looking for something like "for each" input.

the format off the numbers is 1 000,00 (space as thousand separator and , as decimal separator).

My inputs are in and array so the ID's and NAME's is like this:

input_sum1[0]
input_sum1[1]
input_sum1[2]

input_sum2[0]
input_sum2[1]
input_sum2[2]

Any suggestions?

Thanks in advance!

+3  A: 

A jQuery example. Provided a class name for your text boxes.

Working Demo

   <script>
        $(document).ready ( function () {
            $("#btn1").click ( function () {
              var resultVal = 0.0;
               $(".test").each ( function() {
                   resultVal += parseFloat ( $(this).val().replace(/\s/g,'').replace(',','.'));
                });
                alert ( resultVal );  
            });
        });
    </script>

    <input type="text" value="10" class="test" />
        <input type="text" value="20" class="test" />
        <input type="text" value="30.50" class="test" />
        <input type="text" value="1" class="test" />
        <input type="text" value="1" class="test" />
        <br />
        <button id="btn1">click</button>
rahul
1. You've assumed jQuery, which OP didn't list. 2. You've ignored the space and comma stuff. 3. There's no need for all of the class attributes.
T.J. Crowder
+1  A: 
  1. Give your form an id, it makes life easier.
  2. Get a reference to the form object via document.getElementById (or if you're using Prototype or jQuery, they have shorthand ways to do that).
  3. Loop through the form's elements array.
  4. Test each element to see if it's a text input field.
  5. If it is, retrieve its value property; it'll be a string.
  6. Use a regexp on it to remove spaces.
  7. Probably need to convert the commas to dots, but I haven't tested that; if so, another regexp.
  8. Use parseFloat to get the value.
  9. Add it to your sum.
  10. Profit
T.J. Crowder
+1  A: 

You don't get locale-aware number parsing in JavaScript, so you'll have to do a string replacement to get something parseFloat() will handle:

<div id="inputs">
    <input type="text" />
    <input type="text" />
    ...
</div>
<p>
    <input type="button" id="summer" value="Sum" />
    <input type="text" id="sum" />
</p>

<script type="text/javascript">
    document.getElementById('summer').onclick= function() {
         var sum= 0;
         var inputs= document.getElementById('inputs').getElementsByTagName('input');
         for (var i= inputs.length; i-->0;) {
             var v= inputs[i].value.split(',').join('.').split(' ').join('');
             if (isNaN(+v))
                 alert(inputs[i].value+' is not a readable number');
             else
                 sum+= +v;
         }
         document.getElementById('sum').value= sum;
    };
</script>

(You don't need a <form> element or any input names if it's a purely client-side thing you don't ever expect to submit.)

Note this uses floating point numbers, so the sum of 0.1 and 0.2 may not be exactly what you think. If you are looking at money amounts, floating point isn't suitable and you'll have to come up with a fixed-point or decimal-based number parser.

bobince
FYI: Javascript replace() function expects a RegExp. If passing a string does in fact work, it will not work consistently across browsers. Additionally, it does not do a global replace, just the first instance.
Josh Stodola
A string argument to replace() does work fine, but it's still interpreted as a regular expression. It would nonetheless work here as the characters involved are not ‘special’ in regex, but you're right that replace() is often a nasty trap. I've changed it to use the split/join idiom for simple string replacement, which I much prefer (but didn't want to have to explain!)
bobince
Look at my edited question, i can't use "<div id=""> because the inputs is in a table and i want to calculate two different sums in the same table. So the div would have taken them all into the calculation.
Filip Palm