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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With