How get total sum from input box values using Javascript?
Asked Answered
A

9

23

I am not perfect in Javascript.. I want to show total sum of values entered in qty input boxes in next input box named total without refreshing page. Can anyone will help me to figure it out..?

Here is 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>

Here is my html code:

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"/>

here is screen shot here is screen shot

Amandaamandi answered 24/11, 2012 at 11:28 Comment(3)
@SwapnilBhavsar Put your code in the question instead of a comment.Codeine
So you know, the id attribute in HTML must be unique meaning that you can't use it in more than one element per page.Bina
id must be unique. use different id for each text boxPhenazine
M
62

Try:

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;
}
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"/>
Marquittamarr answered 24/11, 2012 at 11:52 Comment(0)
P
20

$(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>
Pulsation answered 17/6, 2016 at 11:15 Comment(0)
S
6

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>

Example: http://jsfiddle.net/fRd9N/1/

Sprung answered 24/11, 2012 at 12:0 Comment(1)
I know this is a fairly old question, but props to @Burlak llia. This was exactly something that I need right now!Ideomotor
I
1

To sum with decimal use this:

In the javascript change parseInt with parseFloat and add this line tot.toFixed(2); for this result:

    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);
}

Use step=".01" min="0" type="number" in the input filed

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"/>
Imhoff answered 16/11, 2019 at 16:39 Comment(0)
M
1

Here is the Complete Solutions [Tested 100% Working]

<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>
Mantel answered 12/9, 2021 at 4:10 Comment(0)
C
0

Try this:

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)

}
Carreon answered 24/11, 2012 at 11:56 Comment(0)
S
0

I need to sum the span elements so I edited Akhil Sekharan's answer below.

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)

You can change the elements with other elements link will guide you with editing.

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

Spectroscope answered 13/5, 2016 at 8:49 Comment(0)
S
0

Here's a simpler solution using what Akhil Sekharan has provided but with a little change.

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;
Simonsimona answered 20/9, 2018 at 11:41 Comment(0)
C
0

I try the code by Waruna Manujula above and working just fine as example. But, how if I want to get the data from mysql and run the sum?. I try do like below but the sum is not function?. I know I must edit some script, but I dont know how to do it..

            <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>
Coliseum answered 2/7, 2021 at 5:7 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.