【问题标题】:How get total sum from input box values using Javascript?如何使用 Javascript 从输入框值中获取总和?
【发布时间】:2012-11-12 12:10:38
【问题描述】:

我在 Javascript 方面并不完美。我想在不刷新页面的下一个名为 total 的输入框中显示在 qty 输入框中输入的值的总和。谁能帮我弄清楚..?

这里是javascript

 <script type="text/javascript"> 
 var howmanytoadd = 2;
 var rows;

 function calc() {
     var tot = 0;
     for (var i = 0; i < rows.length; i++) {
         var linetot = 0;
         rows[i].getElementsByTagName('input')[howmanytoadd].value = linetot;
         tot += linetot;
     }
     document.getElementById('total').value = tot
 }
 onload = function () {
     rows = document.getElementById('tab').getElementById('qty1');
     for (var i = 0; i < rows.length; i++) {
         rows.getElementsByTagName('input')[i].onkeyup = calc;
     }
 }
</script>

这是我的html代码:

Qty1 : <input type="text" name="qty1" id="qty"/><br>
Qty2 : <input type="text" name="qty2" id="qty"/><br>
Qty3 : <input type="text" name="qty3" id="qty"/><br>
Qty4 : <input type="text" name="qty4" id="qty"/><br>
Qty5 : <input type="text" name="qty5" id="qty"/><br>
Qty6 : <input type="text" name="qty6" id="qty"/><br>
Qty7 : <input type="text" name="qty7" id="qty"/><br>
Qty8 : <input type="text" name="qty8" id="qty"/><br>
<br><br>
Total : <input type="text" name="total" id="total"/>

这是屏幕截图

【问题讨论】:

  • @SwapnilBhavsar 将您的代码放在问题中而不是评论中。
  • 所以您知道,HTML 中的id 属性必须是唯一的,这意味着您不能在每页多个元素中使用它。
  • id 必须是唯一的。为每个文本框使用不同的 id

标签: javascript sum calculator


【解决方案1】:

试试:

Qty1 : <input onblur="findTotal()" type="text" name="qty" id="qty1"/><br>
Qty2 : <input onblur="findTotal()" type="text" name="qty" id="qty2"/><br>
Qty3 : <input onblur="findTotal()" type="text" name="qty" id="qty3"/><br>
Qty4 : <input onblur="findTotal()" type="text" name="qty" id="qty4"/><br>
Qty5 : <input onblur="findTotal()" type="text" name="qty" id="qty5"/><br>
Qty6 : <input onblur="findTotal()" type="text" name="qty" id="qty6"/><br>
Qty7 : <input onblur="findTotal()" type="text" name="qty" id="qty7"/><br>
Qty8 : <input onblur="findTotal()" type="text" name="qty" id="qty8"/><br>
<br><br>
Total : <input type="text" name="total" id="total"/>


    <script type="text/javascript">
function findTotal(){
    var arr = document.getElementsByName('qty');
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
    }
    document.getElementById('total').value = tot;
}

    </script>

【讨论】:

    【解决方案2】:

    试试这个:

    function add() 
    {
      var sum = 0;
      var inputs = document.getElementsByTagName("input");
      for(i = 0; i <= inputs.length; i++) 
      {
       if( inputs[i].name == 'qty'+i) 
       {
         sum += parseInt(input[i].value);
       }
      }
      console.log(sum)
    
    }
    

    【讨论】:

      【解决方案3】:

      Javascript:

      window.sumInputs = function() {
          var inputs = document.getElementsByTagName('input'),
              result = document.getElementById('total'),
              sum = 0;            
      
          for(var i=0; i<inputs.length; i++) {
              var ip = inputs[i];
      
              if (ip.name && ip.name.indexOf("total") < 0) {
                  sum += parseInt(ip.value) || 0;
              }
      
          }
      
          result.value = sum;
      }​   
      

      HTML:

      Qty1 : <input type="text" name="qty1" id="qty"/><br>
      Qty2 : <input type="text" name="qty2" id="qty"/><br>
      Qty3 : <input type="text" name="qty3" id="qty"/><br>
      Qty4 : <input type="text" name="qty4" id="qty"/><br>
      Qty5 : <input type="text" name="qty5" id="qty"/><br>
      Qty6 : <input type="text" name="qty6" id="qty"/><br
      Qty7 : <input type="text" name="qty7" id="qty"/><br>
      Qty8 : <input type="text" name="qty8" id="qty"/><br>
      <br><br>
      Total : <input type="text" name="total" id="total"/>
      
      <a href="javascript:sumInputs()">Sum</a>
      

      示例:http://jsfiddle.net/fRd9N/1/

      【讨论】:

      • 我知道这是一个相当古老的问题,但支持@Burlak llia。这正是我现在需要的东西!
      【解决方案4】:

      我需要对 span 元素求和,所以我在下面编辑了 Akhil Sekharan 的答案。

      var arr = document.querySelectorAll('span[id^="score"]');
      var total=0;
          for(var i=0;i<arr.length;i++){
              if(parseInt(arr[i].innerHTML))
                  total+= parseInt(arr[i].innerHTML);
          }
      console.log(total)
      

      您可以使用其他元素更改元素链接将指导您进行编辑。

      https://www.w3.org/TR/css3-selectors/#attribute-substrings

      【讨论】:

        【解决方案5】:

        $(document).ready(function(){
        
        		//iterate through each textboxes and add keyup
        		//handler to trigger sum event
        		$(".txt").each(function() {
        
        			$(this).keyup(function(){
        				calculateSum();
        			});
        		});
        
        	});
        
        	function calculateSum() {
        
        		var sum = 0;
        		//iterate through each textboxes and add the values
        		$(".txt").each(function() {
        
        			//add only if the value is number
        			if(!isNaN(this.value) && this.value.length!=0) {
        				sum += parseFloat(this.value);
        			}
        
        		});
        		//.toFixed() method will roundoff the final sum to 2 decimal places
        		$("#sum").html(sum.toFixed(2));
        	}
        body {
        				font-family: sans-serif;
        			}
        			#summation {
        				font-size: 18px;
        				font-weight: bold;
        				color:#174C68;
        			}
        			.txt {
        				background-color: #FEFFB0;
        				font-weight: bold;
        				text-align: right;
        			}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        
        <table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
        	<tr>
        		<td width="40px">1</td>
        		<td>Butter</td>
        		<td><input class="txt" type="text" name="txt"/></td>
        	</tr>
        	<tr>
        		<td>2</td>
        		<td>Cheese</td>
        		<td><input class="txt" type="text" name="txt"/></td>
        	</tr>
        	<tr>
        		<td>3</td>
        		<td>Eggs</td>
        		<td><input class="txt" type="text" name="txt"/></td>
        	</tr>
        	<tr>
        		<td>4</td>
        		<td>Milk</td>
        		<td><input class="txt" type="text" name="txt"/></td>
        	</tr>
        	<tr>
        		<td>5</td>
        		<td>Bread</td>
        		<td><input class="txt" type="text" name="txt"/></td>
        	</tr>
        	<tr>
        		<td>6</td>
        		<td>Soap</td>
        		<td><input class="txt" type="text" name="txt"/></td>
        	</tr>
        	<tr id="summation">
        		<td>&nbsp;</td>
        		<td align="right">Sum :</td>
        		<td align="center"><span id="sum">0</span></td>
        	</tr>
        </table>

        【讨论】:

          【解决方案6】:

          这是一个使用 Akhil Sekharan 提供的更简单的解决方案,但稍作改动。

          var inputs = document.getElementsByTagName('input');
          
          for (var i = 0; i < inputs.length; i += 1) {
          if(parseInt(inputs[i].value)){
                  inputs[i].value = '';
                 }
              }​​​​
          document.getElementById('total').value = total;
          

          【讨论】:

            【解决方案7】:

            用小数求和:

            在 javascript 中将 parseInt 更改为 parseFloat 并添加这一行 tot.toFixed(2);对于这个结果:

                function findTotal(){
                var arr = document.getElementsByName('qty');
                var tot=0;
                for(var i=0;i<arr.length;i++){
                    if(parseFloat(arr[i].value))
                        tot += parseFloat(arr[i].value);
                }
                document.getElementById('total').value = tot;
                tot.toFixed(2);
            }
            

            在输入字段中使用 step=".01" min="0" type="number"

            Qty1 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty1"/><br>
            Qty2 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty2"/><br>
            Qty3 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty3"/><br>
            Qty4 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty4"/><br>
            Qty5 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty5"/><br>
            Qty6 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty6"/><br>
            Qty7 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty7"/><br>
            Qty8 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty8"/><br>
            <br><br>
            Total : <input type="number" step=".01" min="0" name="total" id="total"/>
            

            【讨论】:

              【解决方案8】:

              我尝试了上面 Waruna Manujula 的代码,并且作为示例运行得很好。但是,如果我想从 mysql 获取数据并运行总和呢?我尝试像下面那样做,但总和不起作用?我知道我必须编辑一些脚本,但我不知道该怎么做..

                          <script type="text/javascript"> 
                          $(document).ready(function()
                          {
                          //iterate through each textboxes and add keyup
                          //handler to trigger sum event
                          $(".txt").each(function() 
                          {
                          $(this).keyup(function()
                          {
                              calculateSum();
                          });
                          });
                          });
                          function calculateSum() 
                          {
                          var sum = 0;
                          //iterate through each textboxes and add the values
                          $(".txt").each(function() 
                          {
                          //add only if the value is number
                          if(!isNaN(this.value) && this.value.length!=0) 
                          {
                              sum += parseFloat(this.value);
                          }
                          });
                          //.toFixed() method will roundoff the final sum to 2 decimal places
                          $("#sum").html(sum.toFixed(2));
                          }
                          </script>
              
                          <table>
                          <tr>
                          <td>1</td>
                          <td>Cost_1</td>
                          <td><input class="txt" type="text" name="txt" value="<?php echo isset($row[0]['cost_1'])?$row[0]['cost_1']:''; ?>"/></td>
                          </tr>
                          <tr>
                          <td>2</td>
                          <td>Cost_2</td>
                          <td><input class="txt" type="text" name="txt" value="<?php echo isset($row[0]['cost_2'])?$row[0]['cost_2']:''; ?>"/></td>
                          </tr>
              
                          <tr id="summation">
                          <td>&nbsp;</td>
                          <td align="left">Total_cost :</td>
                          <td align="center"><span id="sum">0</span></td>
                          </tr>
                          </table>
              

              【讨论】:

                【解决方案9】:

                这里是完整的解决方案 [测试 100% 工作]

                <div id="FormData">
                    Qty1 : <input class="qty" type="text" name="qty" id="qty1" value="" /><br>
                    Qty2 : <input class="qty" type="text" name="qty" id="qty2" value="" /><br>
                    Qty3 : <input class="qty" type="text" name="qty" id="qty3" value="" /><br>
                    Qty4 : <input class="qty" type="text" name="qty" id="qty4" value="" /><br>
                    Qty5 : <input class="qty" type="text" name="qty" id="qty5" value="" /><br>
                    Qty6 : <input class="qty" type="text" name="qty" id="qty6" value="" /><br>
                    Qty7 : <input class="qty" type="text" name="qty" id="qty7" value="" /><br>
                    Qty8 : <input class="qty" type="text" name="qty" id="qty8" value="" /><br>
                    <br><br>
                    Total : <input type="text" name="total" id="total" />
                </div>
                <script>
                    $(function () {
                        $("#FormData").on('change, blur', '.qty', function () {
                            findTotal();
                        })
                    });
                
                    function findTotal() {
                        var maxD = 0;
                        var array = [];
                        var total = 0;
                        $("#FormData .qty").each(function (key, val) {
                            var value = $(this).val();
                
                            if (!isNaN(value) && value.length != 0) {
                                total += parseFloat(value);
                                array[key] = GetMax(parseFloat(value));
                            }
                        })
                
                        maxD = Math.max.apply(Math, array);
                        if (maxD == -Infinity) {
                            maxD = 0;
                        }
                
                        if (maxD != -Infinity) {
                            $("#total").val(total.toFixed(maxD));
                        }
                    }
                    function GetMax(val) {
                        var s = [];
                        s = val.toString().split(".");
                        if (s.length > 1)
                            return s[1].length;
                        else
                            return 0;
                    }
                </script>
                

                【讨论】:

                  猜你喜欢
                  • 2016-07-21
                  • 2022-01-24
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-08-13
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多