最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Calculate the sum off multiple HTML-input values - Stack Overflow

programmeradmin4浏览0评论

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!

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!

Share Improve this question edited May 4, 2012 at 5:50 Donotalo 13k26 gold badges88 silver badges123 bronze badges asked Sep 15, 2009 at 12:53 Filip PalmFilip Palm 1472 gold badges3 silver badges10 bronze badges 2
  • What do the IDs of your form elements look like? – Cᴏʀʏ Commented Sep 15, 2009 at 12:56
  • id="input[0]", id="input[1]", id="input[2]"... – Filip Palm Commented Sep 15, 2009 at 14:37
Add a ment  | 

3 Answers 3

Reset to default 7

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>
  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 mas 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

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 e up with a fixed-point or decimal-based number parser.

发布评论

评论列表(0)

  1. 暂无评论