2015-07-04 2 views
0

Я новичок в программировании, и я пытаюсь создать простой математический скрипт, который определяет цену игры, которую пользователь выбирает и умножает на количество дней, которое они хотят зарезервировать.NaN появляется при попытке рассчитать цену

Это работает, но конечная цена всегда выходит как «NaN» (что, на мой взгляд, означает «Не номер»).

Любая помощь будет принята с благодарностью.

<html> 

<body> 

    <p><strong>Game ID</strong><br> 
    <input type="number" name="gameID" id="gameID" placeholder="1-8"> 

<p><strong>Days you wish to reserve the game for</strong><br> 
    <input type="number" name="daysReserved" id="daysReserved" placeholder="1-5"> 

<br> 

<button type="button" onclick="idToPrice();finalPriceCalculation();">Reserve!</button> 

<p id="totalPriceOutput"></p> 

<script> 
function idToPrice() { 

var id = document.getElementById("gameID").value; 

if (id == 1) { 
var gamePrice = 0.99; 
} else if (id == 2) { 
var gamePrice = 0.99; 
} else if (id == 3) { 
var gamePrice = 1.99; 
} else if (id == 4) { 
var gamePrice = 1.99; 
} else if (id == 5) { 
var gamePrice = 3.99; 
} else if (id == 6) { 
var gamePrice = 3.99; 
} else if (id == 7) { 
var gamePrice = 0.99; 
} else if (id == 8) { 
var gamePrice = 0.99; 
} else { 
document.getElementById("totalPriceOutput").innerHTML = "Error. Your final price could not be calculated because you selected an invalid game ID."; 
} 
} 

function finalPriceCalculation() { 
var daysInputted; 
var gamePrice; 
var finalPrice = daysInputted * gamePrice; 

document.getElementById("totalPriceOutput").innerHTML = "Your final price is &pound;" + finalPrice + "."; 
    } 
</script> 

</body> 

</html> 
+0

Вы, кажется, не присвоить значение ввода с идентификатором 'daysReserved' файл' переменной daysInputted'. –

ответ

1

daysInputted не быть присвоен номером, так что это undefined, так что вы множитесь с undefined, следовательно NaN

0

Нашли проблему
Переменные не получает значение,
Didnt использования parseInt() для получения целочисленных значений
Полный код изменен, протестирована и работает на 100%

 

    <html> 

    <body> 

    <p><strong>Game ID</strong><br> 
     <input type="number" name="gameID" id="gameID" placeholder="1-8"> 

    <p><strong>Days you wish to reserve the game for</strong><br> 
     <input type="number" name="daysReserved" id="daysReserved" placeholder="1-5"> 

     <br> 

     <button type="button" onclick="idToPrice();">Reserve!</button> 

    <p id="totalPriceOutput"></p> 

    <script> 
     function idToPrice() { 

      var id = parseInt(document.getElementById("gameID").value); 
      var days = parseInt(document.getElementById("daysReserved").value); 
      if(!isNaN(id)) 
      { 
       if (id == 1) { 
        var gamePrice = 0.99; 
       } else if (id == 2) { 
        var gamePrice = 0.99; 
       } else if (id == 3) { 
        var gamePrice = 1.99; 
       } else if (id == 4) { 
        var gamePrice = 1.99; 
       } else if (id == 5) { 
        var gamePrice = 3.99; 
       } else if (id == 6) { 
        var gamePrice = 3.99; 
       } else if (id == 7) { 
        var gamePrice = 0.99; 
       } else if (id == 8) { 
        var gamePrice = 0.99; 
       } 
       finalPriceCalculation(id,days); 
      } 
      else { 
       document.getElementById("totalPriceOutput").innerHTML = "Error. Your final price could not be calculated because you selected an invalid game ID."; 
      } 
     } 

     function finalPriceCalculation(gamePrice,daysInputted) { 
      var daysInputted; 
      var finalPrice = parseInt(daysInputted) * parseInt(gamePrice); 

      document.getElementById("totalPriceOutput").innerHTML = "Your final price is £" + finalPrice + "."; 
     } 

     </script> 

1

ПРИМЕЧАНИЕ: Были 3 проблемы в вашем коде. Я скорректировал их все, плюс модифицированные условные выражения с использованием операторов switch case для лучшей читаемости.

. В вашем этом коде var daysInputted и var gamePrice являются местными.

var daysInputted; 
var gamePrice; 
var finalPrice = daysInputted * gamePrice; 

Вы могли бы думать, когда вы звоните idToPrice() метод первым так gamePrice должен быть определен. Но это не так.

Потому что, когда вы говорите var gamePrice внутри метода, gamePrice становится локальной переменной для этого метода и недоступен ни в каком другом методе.

Следовательно, вам нужно либо определить как переменные внутри одного и того же метода, либо сделать их глобальными в методе idToPrice().

. Кроме того, необходимо определить, как daysInputted

var daysInputted = document.getElementById("daysReserved").value; 

.Вы также должны синтаксического анализаdocument.getElementById("gameID").value к Integer

Ваш конечный код полностью рабочий код будет

<body> 

    <p><strong>Game ID</strong><br> 
    <input type="number" name="gameID" id="gameID" placeholder="1-8"> 

<p><strong>Days you wish to reserve the game for</strong><br> 
    <input type="number" name="daysReserved" id="daysReserved" placeholder="1-5"> 

<br> 

<button type="button" onclick="idToPrice();finalPriceCalculation();">Reserve!</button> 

<p id="totalPriceOutput"></p> 

<script> 
function idToPrice() { 

    var id = parseInt(document.getElementById("gameID").value); 

    switch(id) { 
     case 1: 
      gamePrice = 0.99; 
      break; 
     case 2: 
      gamePrice = 0.99; 
      break; 
     case 3: 
      gamePrice = 1.99; 
      break; 
     case 4: 
      gamePrice = 1.99; 
      break; 
     case 5: 
      gamePrice = 3.99; 
      break; 
     case 6: 
      gamePrice = 3.99; 
      break; 
     case 7: 
      gamePrice = 0.99; 
      break; 
     case 8: 
      gamePrice = 0.99; 
      break; 
     default: 
      document.getElementById("totalPriceOutput").innerHTML = "Error. Your final price could not be calculated because you selected an invalid game ID."; 
      break; 
    } 
} 

function finalPriceCalculation() { 
    var daysInputted = document.getElementById("daysReserved").value; 
    var finalPrice = daysInputted * gamePrice; 

    document.getElementById("totalPriceOutput").innerHTML = "Your final price is &pound;" + finalPrice + "."; 
} 
</script> 

</body> 

+0

Это сработало. Благодарю. – MrRetroDinosaur

+0

@MrRetroDinosaur это хорошо. я надеюсь, что вы пометите ответ как правильный :) Все самое лучшее – Shri

0

Ваш код JS может быть:

function idToPrice() { 
var id = document.getElementById("gameID").value, 
    gamePrice, daysInputted, finalPrice; //It is a good practice to define variables at the top of the function, check "variable hoisting". 
if (id === 1) { // It is a good practice to use "===" for checking value and type 
    gamePrice = 0.99; 
} else if (id === 2) { 
    gamePrice = 0.99; 
} else if (id === 3) { 
    gamePrice = 1.99; 
} else if (id === 4) { 
    gamePrice = 1.99; 
} else if (id === 5) { 
    gamePrice = 3.99; 
} else if (id === 6) { 
    gamePrice = 3.99; 
} else if (id === 7) { 
    gamePrice = 0.99; 
} else if (id === 8) { 
    gamePrice = 0.99; 
} 
if (gamePrice) { 
    daysInputted = document.getElementById("daysReserved").value || 0; 
    finalPrice = daysInputted * gamePrice; 
} 

if (finalPrice) { 
    document.getElementById("totalPriceOutput").innerHTML = "Your final price is &pound;" + finalPrice + "."; 
} else { 
    document.getElementById("totalPriceOutput").innerHTML = "Error. Your final price could not be calculated because you selected an invalid game ID."; 
} 
} 

И ваш HTML код:

<button type="button" onclick="idToPrice()">Reserve!</button> 
Смежные вопросы