简体   繁体   English

Javascript计算多个HTML输入值的总和

[英]Javascript Calculate the sum off multiple HTML-input values

im looking for some Javascript code to calculate the sum off multiple HTML-input values. 我正在寻找一些Javascript代码来计算多个HTML输入值的总和。 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). 数字格式为1 000,00(空格为千位分隔符,小数分隔符)。

My inputs are in and array so the ID's and NAME's is like this: 我的输入是和数组,所以ID和NAME是这样的:

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

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

Any suggestions? 有什么建议么?

Thanks in advance! 提前致谢!

A jQuery example. 一个jQuery示例。 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. 给你的表单一个id ,它让生活更轻松。
  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). 通过document.getElementById获取对表单对象的引用(或者如果您使用的是Prototype或jQuery,它们可以使用简写的方法)。
  3. Loop through the form's elements array. 循环遍历表单的elements数组。
  4. Test each element to see if it's a text input field. 测试每个元素以查看它是否是文本输入字段。
  5. If it is, retrieve its value property; 如果是,检索其value属性; 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. 使用parseFloat获取值。
  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: 您没有在JavaScript中获得可识别区域设置的数字解析,因此您必须执行字符串替换以获取parseFloat()将处理的内容:

<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.) (如果您不希望提交纯粹的客户端内容,则不需要<form>元素或任何输入名称。)

Note this uses floating point numbers, so the sum of 0.1 and 0.2 may not be exactly what you think. 请注意,这使用浮点数,因此0.1和0.2之和可能与您的想法不完全相同。 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. 如果您正在查看金额,浮点数不合适,您将不得不想出一个定点或基于十进制的数字解析器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM