NaN appears when trying to calculate price - javascript

I am new to programming, and am trying to create a simple mathematical script that determines the price of the game the user selects and multiplies that by the number of days they wish to reserve the game.
It works, but the final price always comes out as 'NaN' (which I believe stands for 'Not a Number').
Any help will be greatly appreciated.
<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 £" + finalPrice + ".";
}
</script>
</body>
</html>

NOTE: There were 3 problems in your code. I have corrected them all, plus modified conditionals using switch case statements for better readability.
1. In your this code, your var daysInputted and var gamePrice are both local.
var daysInputted;
var gamePrice;
var finalPrice = daysInputted * gamePrice;
You might be thinking when you are calling idToPrice() method first so gamePrice must be defined. But it is not so.
Because when you say var gamePrice inside a method, gamePrice becomes a local variable for that method and it is not accessible in any other method.
Hence you either need to define both the variables inside the same method or make them global in the idToPrice() method.
2. You also need to define daysInputted as
var daysInputted = document.getElementById("daysReserved").value;
3. you also need to parse document.getElementById("gameID").value to Integer
Your final code fully working code will be
<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 £" + finalPrice + ".";
}
</script>
</body>

daysInputted is not being assigned a number so it's undefined, so you are multiplying with undefined, hence NaN

Found problem
The variables are not getting value,
Didnt use parseInt() to get integer values
Complete code modified, tested and works 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>

Your JS code could be:
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 £" + finalPrice + ".";
} else {
document.getElementById("totalPriceOutput").innerHTML = "Error. Your final price could not be calculated because you selected an invalid game ID.";
}
}
And, your HTML code:
<button type="button" onclick="idToPrice()">Reserve!</button>

Related

Javascript - div innerHTML does not change

var score = 0, time = 1, heart = 3;
window.onload = function() {
var input = document.getElementById("wordTyped");
var timeLeft = document.getElementById("time");
var life = document.getElementById("life");
input.addEventListener("click", timer, false);
function timer() {
var id = setInterval(countdown, 10);
function countdown() {
input.removeEventListener("click", timer, false);
timeLeft.innerHTML = "Time left: " + (time - 0.01).toFixed(2) + "s";
time = 1 * (time - 0.01).toFixed(2);
if (time == 0 && life.innerHTML == "") {
clearInterval(id);
} else if (time == 0) {
--heart;
time = 1;
life(heart);
}
}
function life(heart) {
heart *= 1; // To make sure it is a number type
console.log(heart);
switch (heart) {
case 2:
life.innerHTML = "❤️❤️";
console.log(life.innerHTML);
break;
case 1:
life.innerHTML = "❤️";
console.log(life.innerHTML);
break;
case 0:
default:
life.innerHTML = "";
console.log(life.innerHTML);
break;
}
/*if(heart === 2) {
life.innerHTML = "❤️❤️";
}
else if(heart == 1) {
life.innerHTML = "❤️";
}
else {
life.innerHTML = "";
}*/
}
}
}
<div id="wordGenerated">illustration</div>
<input id="wordTyped" type="text" />
<div id="time">Time left: 1.00s</div>
<div id="score">Score: 0</div>
<div id="life">❤️❤️❤️</div>
I'm not sure what is wrong within the function life(heart).
I'm trying to decrease the amount of '❤️' by one as the time hit 0 and reset back to its original value, repeating until heart equals to 0.
If I use life.innerHTML = " example " outside the function timer() scope, it will work.
Using console.log(), it shows that life.innerHTML has changed, however, the display of HTML document stays the same and I don't understand why.
I've tried .nodeValue, .innerText, and .textContent, and all still gave the same result
There is a conflict usage with life variable and life() function. Change life() function name to something else like updateLife() and your code works,
Note: You can't have the same name for variable or function or Objects within the scopes.
Demo
var score = 0, time = 1, heart = 3;
window.onload = function() {
var input = document.getElementById("wordTyped");
var timeLeft = document.getElementById("time");
var life = document.getElementById("life");
input.addEventListener("click", timer, false);
function timer() {
var id = setInterval(countdown, 10);
function countdown() {
input.removeEventListener("click", timer, false);
timeLeft.innerHTML = "Time left: " + (time - 0.01).toFixed(2) + "s";
time = 1 * (time - 0.01).toFixed(2);
if (time == 0 && life.innerHTML == "") {
clearInterval(id);
} else if (time == 0) {
--heart;
time = 1;
updateLife(heart);
}
}
function updateLife(heart) {
heart *= 1; // To make sure it is a number type
console.log(heart);
switch (heart) {
case 2:
life.innerHTML = "❤️❤️";
console.log(life.innerHTML);
break;
case 1:
life.innerHTML = "❤️";
console.log(life.innerHTML);
break;
case 0:
default:
life.innerHTML = "";
console.log(life.innerHTML);
break;
}
/*if(heart === 2) {
life.innerHTML = "❤️❤️";
}
else if(heart == 1) {
life.innerHTML = "❤️";
}
else {
life.innerHTML = "";
}*/
}
}
}
<div id="wordGenerated">illustration</div>
<input id="wordTyped" type="text" />
<div id="time">Time left: 1.00s</div>
<div id="score">Score: 0</div>
<div id="life">❤️❤️❤️</div>
there is a conflict between life and life function so you can go like $("#life").innerHTML="" or any thing else

Javascript: assigning an input letter a specific value

I'm having trouble assigning an input a certain value. For example, when the user enters a letter through the TicketType prompt, I want that letter to be converted into a number. So say they enter 'B' as their TicketType, I then want 'B' to be converted into 50 so I can latter calculate a total cost. At the moment TotalPayment is only displaying NaN and I'm so confused.
This is my JavaScript Code:
function ticket() {
var TicketType;
TicketType = prompt("Please enter the type of ticket you require!");
document.write("<br>");
var TicketQty;
TicketQty = prompt("Please enter the number of tickets you require!");
TicketQty = parseInt(TicketQty);
document.write("Number of Tickets:" + TicketQty);
document.write("<br>");
var TotalPayment =(TicketPrice) * (TicketQty);
document.write("Total Payment is:" + TotalPayment);
var TicketPrice;
TicketPrice = parseInt(TicketPrice);
if (TicketType == A) {
TicketPrice == 100;
}
else if (TicketType == B) {
TicketPrice == 75;
}
else if (TicketType == C){
TicketPrice == 50;
}
else {
document.write("Invalid Ticket Type");
}
}
This is my HTML Code:
<html>
<title>Ticket</title>
<h1>Ticket</h1>
<script src="test.js"> </script>
<script>calculate()</script>
</body>
Try the following:
var TicketType;
var TicketQty;
var TicketPrice;
function calculateticket() {
TicketType = prompt("Please enter the type of ticket you require!");
document.write("<br>");
TicketQty = prompt("Please enter the number of tickets you require!");
testType();
}
calculateticket();
function testType(){
if(TicketType =='A' || TicketType == 'B' || TicketType == 'C'){
if (TicketType == 'A') {
TicketPrice = 100;
} else if (TicketType == 'B') {
TicketPrice = 75;
} else if (TicketType == 'C'){
TicketPrice = 50;
}
TicketQty = parseInt(TicketQty);
document.body.innerHTML += '<span id="text1"></span>';
document.getElementById('text1').innerHTML = 'Total Payment is: '+TicketQty;
document.write("<br>");
var TotalPayment =(TicketPrice) * (TicketQty);
document.body.innerHTML += '<span id="text2"></span>';
document.getElementById('text2').innerHTML = 'Total Payment is: '+TotalPayment;
TicketPrice = parseInt(TicketPrice);
}
else {
if(document.getElementById('text1') != null){
document.getElementById('text1').innerHTML = '';
}
if(document.getElementById('text2') != null){
document.getElementById('text2').innerHTML = '';
}
document.write("Invalid Ticket Type");
}
}
You need to change two things:
1: String comparation
if (TicketType == A)
to
if (TicketType == 'A')
2: wrong assign
TicketPrice == 100
to
TicketPrice = 100
Your string comparison is completely wrong. I'm confining my answer to that because it's what you were asking about.
if (TicketType == A) {
Needs to be:
if (TicketType === "A") {
Also, you have to be clear on assignment '=' vs. comparison '=='.
Whole section should be more like this:
if (TicketType === "A") {
TicketPrice = 100;
} else if (TicketType === "B") {
TicketPrice = 75;
} else if (TicketType === "C")
TicketPrice = 50;
else {
document.write("Invalid Ticket Type");
}
Look into switch statements when you have a chained if-then-elseif
There are other things wrong with your code. Here's a jsfiddle with some fixes and improvements.

I need a button NOT to disapear

I am making a javascript code that has a button and when I click on it, it displays one of 5 symbols but when I click the button, it shows the random symbol but the button disapears. I'm new to javascript so can I please get some help?
<script>
function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0) {
document.write("\u2663");
}
if (slot1 == 1) {
document.write("\u2665");
}
if (slot1 == 2) {
document.write("\u2666");
}
if (slot1 == 3) {
document.write("\u2660");
}
if (slot1 == 4) {
document.write("7");
}
}
</script>
<button type="button" value="Spin" name="SPIN"onClick="slots(); return false;"></button>
When you write document.write() the screen refreshes, so I guess you could do something like this:
<script>
function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0) {
document.getElementById('value').innerHTML = "\u2663";
}
if (slot1 == 1) {
document.getElementById('value').innerHTML = "\u2665";
}
if (slot1 == 2) {
document.getElementById('value').innerHTML = "\u2666";
}
if (slot1 == 3) {
document.getElementById('value').innerHTML = "\u2660";
}
if (slot1 == 4) {
document.getElementById('value').innerHTML = "7";
}
}
</script>
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>
Slightly optimized version of otrebla's code, see it in action:
function slots() {
var slot1 = Math.floor(Math.random() * 5);
var value = document.getElementById('value');
switch (slot1) {
case 0:
value.innerHTML = "\u2663";
break;
case 1:
value.innerHTML = "\u2665";
break;
case 2:
value.innerHTML = "\u2666";
break;
case 3:
value.innerHTML = "\u2660";
break;
case 4:
value.innerHTML = "7";
break;
}
}
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>

Javascript Check variable.Then gain ++ per second

I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}

Input not being assigned in a switch situation

So I know ive cluttered this to High heaven and back but it should work. My only problem is that im not getting a returned value for my input of homeValue. Therefore none of my taxes can be applied. Here is the original problem statement:
Ps. Sorry for just straight asking this the other day, I had left my Flashdrive at home and have this due later this week so I wanted to get it posted today.
You have been asked to write a property tax program for the tri-county area. If you live in Charleston county then you owe 1 percent of your home's value if it's less than or equal to $50,000. You owe 1.50 percent if it's greater than $50,000 but not greater than $150,000 and 2 percent if it's greater than $150,00. If you live in Dorchester county then you owe 1.25 percent of your home's value if it's less than or equal to $50,000. You owe 1.50 percent if it's greater than $50,000 but not greater than $150,000 and 1.75 percent if it's greater than $150,000. If you live in Berkeley county then you owe 2 percent of your home's value if it's less than or equal to $50,000 of value, 2.25 percent if it's greater than $50,000 but not greater than $150,000 and 2.75 percent if it's greater than $150,000.
At the end of the program they want to see the value for the home, the county it resides in and the property tax owed. You must use Switch logic when selecting the county in your code.
<script type="text/javascript">
<!--
//assumptions
var lowValue = 50000;
var medValue = 150000;
var highValue, taxCode, valueCode;
var charleston1 = .01;
var charleston2 = .015;
var charleston3 = .02;
var dorchester1 = .0125;
var dorchester2 = .015;
var dorchester3 = .0175;
var berkeley1 = .02;
var berkeley2 = .0225;
var berkeley3 = .0275;
var county, taxOwed, tax;
var charleston, dorchester, berkeley;
var homeValue = 0;
//input
homeValue = prompt("How much is the property worth?","");
homeValue = parseInt(homeValue);
county = prompt("Which county do you live in?", "");
//calculations
switch (county)
{
case "charleston":
taxCode = charleston;
break;
case "dorchester":
taxCode = dorchester;
break;
case "berkeley":
taxCode = berkeley;
break;
default:
alert("You didnt enter a proper county.");
break;
}
switch (homeValue)
{
case (homeValue):
valueCode = lowValue;
break;
case (homeValue <= medValue):
valueCode = medValue;
break;
case (homeValue > medValue):
valueCode = highValue
default:
break;
}
switch (taxCode)
{
case (charleston && lowValue):
homeTax = charleston1;
break;
case (charleston && medValue):
homeTax = charleston2;
break;
case (charleston && highValue):
homeTax = charleston3;
break
case (dorchester && lowValue):
homeTax = dorchester1;
break;
case (dorchester && medValue):
homeTax = dorchester2
break
case (dorchester && highValue):
homeTax = dorchester3
break;
case (berkeley && lowValue):
homeTax = berkeley1;
break;
case (berkeley && medValue):
homeTax = berkeley2;
break;
case (berkeley && highValue):
homeTax = berkeley3;
break;
Default:
alert("somethings wrong");
}
totalTax = homeValue * homeTax;
//output
document.write("$" + homeValue + " house in " + county + " County.");
document.write("Tax owed: $" + totalTax);
// -->
</script>
var county, homeValue, taxOwed;
//input
homeValue = prompt("How much is the property worth?","");
homeValue = parseInt(homeValue);
county = prompt("Which county do you live in?", "");
switch (county)
{
case "charleston":
if (homeValue <= 50000) {
taxOwed = homeValue * 0.01;
}
else if (homeValue > 50000 && homeValue < 150000) {
taxOwed = homeValue * 0.015;
}
else {
taxOwed = homeValue * 0.02;
}
break;
case "dorchester":
if (homeValue <= 50000) {
taxOwed = homeValue * .0125;
}
else if (homeValue > 50000 && homeValue < 150000) {
taxOwed = homeValue * 0.015;
}
else {
taxOwed = homeValue * 0.0175;
}
break;
case "berkeley":
if (homeValue <= 50000) {
taxOwed = homeValue * 0.02;
}
else if (homeValue > 50000 && homeValue < 150000) {
taxOwed = homeValue * 0.0225;
}
else {
taxOwed = homeValue * 0.0275;
}
break;
default:
alert("You didnt enter a proper county.");
break;
}
//output
alert("Your house in " + county + " has a value of $" + homeValue + " and tax owed is $" + taxOwed);

Categories

Resources