Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the sum of values in input elements using JavaScript

I'm trying to compute the sum of many inputs that are displayed, in order to make an invoice. All products that must be invoiced are recorder in my database, and I wrote this JavaScript function to calculate the total:

<script type="text/javascript">
function getItems()
 {
 var items = new Array();
 var itemCount = document.getElementsByClassName("items");
 var total = 0;
 for(var i = 0; i < itemCount.length; i++)
 {
     total = total +  document.getElementById("p"+(i+1)).value;
 }

 return total;
 document.getElementById('tot').value= total;
 }
 getItems()</script>

The problem is that I get Uncaught TypeError: Cannot read property 'value' of null on the line total = total + document.getElementById("p"+(i+1)).value;

I really do not understand why, because all my variables are declared.

like image 613
Stanislas Piotrowski Avatar asked Jun 30 '26 04:06

Stanislas Piotrowski


1 Answers

You already got the elements by using getElementsByClassName, why you are getting it again by id? You can try following:

function getItems()
{
    var items = document.getElementsByClassName("items");
    var itemCount = items.length;
    var total = 0;
    for(var i = 0; i < itemCount; i++)
    {
        total = total +  parseInt(items[i].value);
    }
    document.getElementById('tot').value = total;
}
getItems();​
like image 65
MJ Fathinia Avatar answered Jul 01 '26 18:07

MJ Fathinia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!