tags:

views:

63

answers:

4

I would like to compute sum of subtotals dynamically but i always get this error:

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

My javascript code:

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

The item hasn't been defined in your page - double check to make sure it's actually there in the source.

Steve
When I do example: alert(document.getElementById('item_subtotal[25]').value); will get the value
anonymous2
A: 

Your problem may be those square brackets.

From the html4 spec:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Weston C
square brackets are fine, and also regularly used for the benefit of php scripts
bemace
A: 

You're pretty close but you need to check for fields with empty values instead of just assuming they contain numbers. It works with only minor modifications in this JS fiddle

Changed your function to this:

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;
}
bemace
There's a problem with this line i guess: document.getElementById('item_subtotal[' + cnt + ']'); since it will prompt that if (parseInt(subtot.value) == '') is null. HELP
anonymous2
But if I test it with document.getElementById('item_subtotal[1]') it works okay
anonymous2
I'm not sure what you're saying. It's easy enough to check for null if you need to, but since you should know how many elements there are it doesn't seem particularly necessary.
bemace
I ran the program and there's an error: if (parseInt(subtot.value) == '') is null
anonymous2
@anonymous2 - I've updated the code
bemace
+2  A: 

I would look if the id exist, ie

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

Furthermore, I would use the Firebug extension for Firefox to look at what might have gone 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++;
  }
Aspelund