Search code examples
javascriptgetelementbyidparsefloat

parseFloat() Not Working


I was wondering what am I doing wrong? I am trying to put some numbers into javascript vars and add them but when I uncomment the line that prints the values they are all NaN.

<div id="priceDisplayPoolHeating">8.00</div>
<div id="priceDisplayPetFee">7.00</div>
<div id="priceDisplayPropertyDamageProtection">4.00</div>
<div id="priceDisplayVacationPackageTotal">9.80</div>
function recalculateGrandTotal() {
  var alreadySetCosts = 30.00;

  var thePoolHeatingFeeRounded = parseFloat(document.getElementById("priceDisplayPoolHeating").value);
  var thePetFeeRounded = parseFloat(document.getElementById("priceDisplayPetFee").value);
  var thePropertyDamageProtectionFeeRounded = parseFloat(document.getElementById("priceDisplayPropertyDamageProtection").value);

  var theGrandTotal = alreadySetCosts + thePoolHeatingFeeRounded + thePetFeeRounded + thePropertyDamageProtectionFeeRounded;

  document.getElementById("priceDisplayVacationPackageTotal").innerHTML = theGrandTotal;
  document.write('<br/>The Vars: ' + alreadySetCosts + '<br/>' + thePoolHeatingFeeRounded + '<br/>' + thePetFeeRounded + '<br/>' + thePropertyDamageProtectionFeeRounded + '<br/>' + theGrandTotal);
}

Solution

  • It's because div tags don't have a value.

    <div id="priceDisplayPoolHeating" class="priceDisplay">8.00</div>
    

    You have to change your JS lines with code like this:

    document.getElementById("priceDisplayPoolHeating").value
    

    To instead get the text:

    document.getElementById("priceDisplayPoolHeating").innerHTML
    

    When you're debugging you should try to see what is contained in values like document.getElementById("priceDisplayPoolHeating").value. If you had done that you would have seen it returned undefined and parseFloat(undefined); returns NaN.