Javascript addition giving me NaN

时间:2018-02-03 08:28:48

标签: javascript

I have a Javascript code as written below. Everything is working fine except the fact the net value that is the grand total of addition of all the total values, is coming as NaN. I have used parseFloat() but still the result is NaN. But I am getting the all the total values. Any help is welcome.

window.onkeyup=function() {

  var items = document.querySelectorAll(".item");
  var itemsArray = Array.prototype.slice.call(items,0);
  var unit, rate, total, net, tax, margin, rateamount = 0;
  itemsArray.forEach(function(el){
    unit = el.querySelector('input[name="unit[]"]').value;
    rate = el.querySelector('input[name="rate[]"]').value;
    tax = el.querySelector('input[name="tax[]"]').value;
    margin = el.querySelector('input[name="margin[]"]').value;
    el.querySelector('input[id="marginrate[]"]').options[el.querySelector('input[id="marginrate[]"]').selectedIndex].text;
    var rateMargin =el.querySelector('[name="marginrate[]"]').selectedIndex;



    if (rateMargin==1) {rateamount=margin/100}
    if (rateMargin==0) {rateamount=margin}


    total = (parseFloat(unit * rate) + parseFloat(rateamount))-parseFloat(tax/100);
    alert(total);
    el.querySelector('input[name="total[]"]').value = total;
    net+= parseFloat(total);
  });

  document.getElementById('net').value=net;
}

1 个答案:

答案 0 :(得分:2)

You never initialized net, so when you do net += parseFloat(total); you're adding a number to undefined, which results in NaN. You need to initialize it to 0.

You also should be calling parseFloat on the values that are read from the inputs, not on the results of arithmetic operations (they always return numbers, you don't need to parse them).

window.onkeyup = function() {

  var items = document.querySelectorAll(".item");
  var itemsArray = Array.prototype.slice.call(items, 0);
  var unit, rate, total, net = 0, tax, margin, rateamount = 0;
  itemsArray.forEach(function(el) {
    unit = el.querySelector('input[name="unit[]"]').value;
    rate = el.querySelector('input[name="rate[]"]').value;
    tax = el.querySelector('input[name="tax[]"]').value;
    margin = el.querySelector('input[name="margin[]"]').value;
    el.querySelector('input[id="marginrate[]"]').options[el.querySelector('input[id="marginrate[]"]').selectedIndex].text;
    var rateMargin = el.querySelector('[name="marginrate[]"]').selectedIndex;
    
    if (rateMargin == 1) {
      rateamount = margin / 100
    } else if (rateMargin == 0) {
      rateamount = margin
    }

    total = (parseFloat(unit) * parseFloat(rate) + parseFloat(rateamount)) - parseFloat(tax) / 100;
    alert(total);
    el.querySelector('input[name="total[]"]').value = total;
    net += total;
  });

  document.getElementById('net').value = net;
}