Input not being assigned in a switch situation - javascript

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);

Related

if else statement..calculation for the activity level

var bmr=100;
var sum=50;
var caloriesneeded = 0;
var activitylevel = prompt("Enter your activity level ");
document.write( "<p>You need to consume ");
if ( activitylevel == "0"){
document.write (caloriesneeded = bmr * 1.2 );
}
else if (activitylevel == "1-3"){
document.write(caloriesneeded = bmr * 1.375 );
}
else if (activitylevel == "3-5"){
document.write(caloriesneeded = bmr * 1.55 );
}
else if (activitylevel == "6-7"){
document.write (caloriesneeded = bmr * 1.725 );
}
else if (activitylevel == "2x"){
document.write(caloriesneeded = bmr * 1.9 );
}
else {
document.write("invalid");
}
if (caloriesneeded > sum){
document.write ("<p>You still can consume " + (caloriesneeded - sum) +
"kcal of food</p>");
}
else if (caloriesneeded == sum){
document.write("<p>You have consumed just enough " + (caloriesneeded -
sum) + "kcal of food</p>");
}
else if (caloriesneeded < sum){
document.write ("<p>You have over consumed " + (sum - caloriesneeded )
+ "kcal of food</p>");
}
Only the first half of the code is working and the calculation for calories needed > sum, calories needed == sum and calories needed < sum does not show any result. Only when the activity level is 'Invalid' then the second part of the code will be working. Anyone spot any errors?
var bmr=100;
var sum=50;
var caloriesneeded = 0;
var activityLevels = {
"0": 1.2,
"1-3": 1.375,
"3-5": 1.55,
"6-7": 1.725,
"2x": 1.9
};
var output = "";
function calculateCaloriesNeeded(activityLevel) {
if ( typeof activityLevels[activityLevel] !== "undefined") {
caloriesneeded = bmr * activityLevels[activityLevel];
return true;
}
return false;
}
var currentActivityLevel = prompt("Enter your activity level ");
if (calculateCaloriesNeeded( currentActivityLevel )) {
// input has been valid
output += "<p>You need to consume " + caloriesneeded + "</p>";
if (caloriesneeded > sum){
output += "<p>You still can consume " + (caloriesneeded - sum) + "kcal of food</p>";
} else if (caloriesneeded == sum){
output += "<p>You have consumed just enough " + (caloriesneeded - sum) + "kcal of food</p>";
} else if (caloriesneeded < sum){
output += "<p>You have over consumed " + (sum - caloriesneeded ) + "kcal of food</p>";
}
} else {
output += "<p>Your input is not valid. Please choose one of “0”, “1-3”, “3-5”, “6-7” or “2x”.</p>";
}
document.write( output );
A little bit cleaner approach.
I am sorry to say but your code is full of bugs.
document.write( "<p>You need to consume "); // missing closing tag </p>
document.write (caloriesneeded = bmr * 1.725 ); // assign and passing a parameter at the same time?
Calculate the value and then pass it to the document eg:
caloriesneeded = bmr * 1.2;
document.write ("<p>"+caloriesneeded+"</p>");
The value passed to the prompt windows are number no need to put them into quotes.
if ( activitylevel == 0){
This is not a range check:
if (activitylevel == "1-3"){
You should do the following:
if (activitylevel >= 1 && activitylevel < 3){
As expressed above the user have no idea what to enter in the prompt window. It would be better to have a list from which the user could choose from.
Here I have made a simple example in how you could potentially make it a better solution.
$("#activeSelection").change(function() {
var bmr = 100;
var sum = 50;
var caloriesneeded = 0;
var $selection = $("#activeSelection").val();
if ($selection == 0) {
caloriesneeded = bmr * 1.2;
$('#calorieResponse').text(caloriesneeded);
} else if ($selection >= 1 && $selection < 3) {
caloriesneeded = bmr * 1.375
$('#calorieResponse').text(caloriesneeded);
} else if ($selection >= 3 && $selection <= 5) {
caloriesneeded = bmr * 1.55
$('#calorieResponse').text(caloriesneeded);
} else if ($selection >= 6 && $selection < 7) {
caloriesneeded = bmr * 1.725;
$('#calorieResponse').text(caloriesneeded);
} else if ($selection >=8 && $selection <=10) {
caloriesneeded = bmr * 1.9
$('#calorieResponse').text(caloriesneeded);
}
if (caloriesneeded > sum){
$('#consume').text("You still can consume " + (caloriesneeded - sum) + "kcal of food");
}
else if (caloriesneeded == sum){
$('#consume').text("You have consumed just enough " + (caloriesneeded -
sum) + "kcal of food");
}
else if (caloriesneeded < sum){
$('#consume').text("You have over consumed " + (sum - caloriesneeded )+ "kcal of food");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Hei, what is your activity level? </span>
<select id="activeSelection">
<option>Please select</option>
<option value="0">Couch potato</option>
<option value="1">Not doing much</option>
<option value="2">Lazy</option>
<option value="3">Little active</option>
<option value="4">Somehow active</option>
<option value="5">Active</option>
<option value="6">Active 2 times a week</option>
<option value="7">Active 3 times a week</option>
<option value="8">Active 4 times a week</option>
<option value="9">Active 5 times a week</option>
<option value="10">Always on the go</option>
</select>
<div>You need to consume: </div><span id="calorieResponse"></span>
<div id="consume"></div>

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

cant get the reset button to reset the pot

for some reason i cant get my reset button to reset the pot i have this as my html code. ive been working at it and cant seem to figure it out im pretty sure im just missing something really important
<button id="reset" onClick="reset()"> Reset </button>
and this as my java for the reset button factor
var pot = 100;
function pull() {
var slot1 = 0;
var slot2 = 0;
var slot3 = 0;
/*generate 3 random numbers, assign to corresponding img1,
img2,img3, swap images in table */
for (var i = 1; i <= 3; i++) {
var fruit = Math.floor((Math.random() * 3) + 1);
document.getElementById(i).src = "img" + fruit + ".gif";
//assign each of the 3 random numbers to a slot value
if (i == 1) {
slot1 = fruit;
}
else if (i == 2) {
slot2 = fruit;
}
else {
slot3 = fruit;
}
}
//add 25 to the pot if the result is 3 of a kind
if (slot1 == slot2 && slot2 == slot3){
pot = pot + 25;
document.getElementById("awnser").innerHTML =
"Jackpot, 3 of a kind! You win $25.00, <br> Pot: $" + pot;
}
//add 10 to pot if the result is a pair
else if (slot1 == slot2 || slot2 == slot3 || slot1 == slot3){
pot = pot + 10;
document.getElementById("awnser").innerHTML = "A pair! You win $10.00.
<br> pot: $" + pot;
}
else {
pot = pot - 120;
if (pot <= 0) {
document.getElementById("awnser").innerHTML = "pot is empty, you are
out of cash."
document.getElementById("stop").disabled = true;
function reset(){
pot = pot + 100;
document.getElementById("reset").reset;
}
}
else {
document.getElementById("awnser").innerHTML = "No match! You loose
$20.00. <br> Pot: $" + pot;
}
}
}

NaN appears when trying to calculate price

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>

Tip Calculator not giving Total Amount

I'm trying to create a tip calculator but I'm having trouble creating a variable that will give me the total amount of the bill. Below is the code, any suggestions?
function tipCalculate (slider, bill){
var tip = document.getElementById('tipamount');
var slideval = document.getElementById('slideval');
var bill = document.getElementById(bill).value;
var prcnt = slider * .01;
var total = Number(bill) + tip;
if (bill == null || bill == '') {
tip.innerHTML = 'Please enter an amount';
return false;
}
if(isNaN(bill)) {
tip.innerHTML = 'Please enter a number';
return false;
}
if(bill >= 0){
tip.innerHTML = '$' + (bill * prcnt) .toFixed(2);
slideval.innerHTML = slider + '%';
}
}
Line 6 is your problem. tip is a dom element and you are trying to add it to a value accessed in the dom i.e bill's value;
This line is not correct:
var total = Number(bill) + tip;

Categories

Resources