开发者

compute sum dynamically with javascript

开发者 https://www.devze.com 2023-01-20 05:39 出处:网络
I would like to compute sum of subtotals dynamically but i always get this error: document.getElementById(\"item_subtotal[\" + cnt + \"]\") is null

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 calcu开发者_运维百科lateTotalAll(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); 
}


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


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


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


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 (".").

0

精彩评论

暂无评论...
验证码 换一张
取 消