Question

I can't get my javascript calculation works for cart.

My HTML part got many other input element except those with "price-" and "qty-" id. Somehow the other input element mess up the array I guess. Sample:

<input type="hidden" id="price-1" value="10.50"/>
<input type="hidden" id="qty-1" value="1"/>
<input type="hidden" id="shipFee-1" value="4.00"/>
<input type="hidden" id="tax-1" value="0.70"/>

<input type="hidden" id="price-2" value="19.20"/>
<input type="hidden" id="qty-2" value="2"/>
<input type="hidden" id="shipFee-2" value="4.00"/>
<input type="hidden" id="tax-2" value="1.30"/>

I want it to alert the total of (price * qty) as "48.9". Here's the problematic javascript part:

var inputs=document.getElementsByTagName('input'),
    total = 0, 
    price = new Array(), 
    qty = new Array();

for (var i = 0 ; i < inputs.length ; i++) {
  if (inputs[i].id.indexOf('price-') == 0) {
    price[i] = parseFloat(document.getElementById(inputs[i].id).value);
    alert(price[i]); //alert result: 10.5 and 19.2
  }
  if (inputs[i].id.indexOf('qty-') == 0) {
    qty[i] = parseInt(document.getElementById(inputs[i].id).value);
    alert(qty[i]); //alert result: 1 and 2
  }
}

alert(price.length); //alert result: 5
alert(qty.length); //alert result: 6

for (i = 0 ; i < price.length ; i++) {
  total = total + price[i] * qty[i];
}
alert (total); //alert result: NaN
Was it helpful?

Solution

Never mind, I found the answer 10 minutes after I posted this question. I feel like an idiot now ==;
I need to use new variable for array instead of "i", since it used for input element array.

var inputs=document.getElementsByTagName('input'),
    total = 0, 
    price = new Array(), 
    qty = new Array(),
    j = 0, k = 0;

for (var i = 0 ; i < inputs.length ; i++) {
  if (inputs[i].id.indexOf('price-') == 0) {
    price[j] = parseFloat(document.getElementById(inputs[i].id).value);
    j++;
  }
  if (inputs[i].id.indexOf('qty-') == 0) {
    qty[k] = parseInt(document.getElementById(inputs[i].id).value);
    k++;
  }
}

for (i = 0 ; i < price.length ; i++) {
  total = total + price[i] * qty[i];
}
alert (total); //alert result: 48.9

OTHER TIPS

You are building the price array based on the 'i' loop counter. The 10.50 goes into price[0], The quanty of 1 that goes with it is put in qty[1], then i goes through values 2 and 3 with no changes to the arrays. Then when i=4, price[4] gets 19.20 and then qty[5] gets 2 then next time through.

The resulting arrays look like

price[0] = 10.5, price[4] = 19.20
qty[1] = 1, qty[5] = 2

When you loop through the last time to try and so the math, you are essentially doing this:

// i = 0
total = total + price[0] * qty [0] // price[0] = 10.50, but qty[0] = undefined, so total = Nan

// i = 1
total = total + price[1] * qty [1] // price[1] = undefined, qty[1] 1, so total = Nan

// etc.

Make sense?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top