Calculate amount dynamically using javascript

I would like to calculate the sum of subtotals dynamically, but always get this error:

document.getElementById("item_subtotal[" + cnt + "]") is null 

My javascript code is:

 function calculateTotalAll(numitems) { var cnt = 1; var totalAmt = 0; while(cnt <= numitems) { totalAmt = parseInt(totalAmt) + parseInt(document.getElementById('item_subtotal[' + cnt + ']').value); cnt++; } document.getElementById('order_total').value = parseInt(totalAmt); } 
+4
source share
4 answers

You are pretty close, but you need to check the fields with empty values, and not just assume that they contain numbers. It only works with minor changes to this JS script

Changed your function:

 function calculateTotal(numitems) { var totalAmt = 0; for (var cnt = 1; cnt <= numitems; cnt++) { var subtotal = document.getElementById('item_subtotal[' + cnt + ']'); if (subtotal.value === null || subtotal.value === '') { continue; } totalAmt += (subtotal.value * 1); } document.getElementById('order_total').innerHTML = totalAmt; } 
0
source

I would see if id exists, i.e.

  while(cnt <= numitems) { var curItem = document.getElementById('item_subtotal[' + cnt + ']'); if(curItem!=null){ totalAmt = parseInt(totalAmt) + parseInt(curItem.value); } cnt++; } 

Also, I would use the Firebug extension for Firefox to see what could go wrong:

  while(cnt <= numitems) { var curItem = document.getElementById('item_subtotal[' + cnt + ']'); if(curItem!=null){ totalAmt = parseInt(totalAmt) + parseInt(curItem.value); }else{ console.log('Couldn\'t find element item_subtotal[' + cnt + ']'); } cnt++; } 
+2
source

The item is not defined on your page - double check to make sure that it is actually present in the source.

0
source

Your problem may be in square brackets.

From html4 spec :

Identifier identifiers and NAME must begin with a letter ([A-Za-z]) and can be performed with any number of letters, numbers ([0-9]), hyphen ("-"), underscore ("_"), colons ( ":") and periods ("").

0
source

All Articles