parseFloat() не работает

Мне было интересно, что я делаю не так? Я пытаюсь поместить некоторые числа в переменные javascript и добавить их, но когда я раскомментирую строку, которая печатает значения, все они равны 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);
}

2 ответа

Решение

Это потому, что теги div не имеют value,

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

Вы должны изменить свои строки JS с кодом, подобным этому:

document.getElementById("priceDisplayPoolHeating").value

Чтобы вместо этого получить текст:

document.getElementById("priceDisplayPoolHeating").innerHTML

Когда вы отлаживаете, вы должны попытаться увидеть, что содержится в таких значениях, как document.getElementById("priceDisplayPoolHeating").value, Если бы вы сделали это, вы бы увидели, что он вернулся undefined а также parseFloat(undefined); возвращается NaN,

Вы пытаетесь получить доступ к атрибуту значения элемента...

document.getElementById("priceDisplayPropertyDamageProtection").value

Вам нужен текстовый контент:

document.getElementById("priceDisplayPropertyDamageProtection").textContent

Надеюсь, это поможет?

Другие вопросы по тегам