I am making a reservation system. I want to program this so that if the user clicks on button with class A, their total price gets increased by 7.50. Same for button with class B, class C etc.
I tried coding it like this:
var price = 0;
if (button.className === "A")
{
price + 7.50;
}
if (button.className === "B")
{
price + 11;
}
if (button.className === "C")
{
price + 13;
}
But the only output I get is 0!
I'm probably making a rookie mistake, but can anyone help me out?
You want +=
price += 13;
This is equiv to:
price = price + 13;
Calling price + 13 will do nothing, since your never re-assigning the result back to price.
There are a couple things I'm hoping you would learn here:
You can write an alert(button.className); at the top of your code to tell you the class name of the button.
Then, as one of the guys pointed out, use else if. For example, if it passes the first condition, it won't have to go through the other two. Here's an example:
var dayToday = 'Monday';
if (dayToday === 'Monday') {
doThis();
}
else if (dayToday === 'Tuesday') {
doThat();
}
// Since today is Monday, it will pass the first "if condition"
// It won't have to check the 2nd condition
And the price + 7.50 just calculates and returns the resulting value, but it doesn't store that value anywhere. What you want to do is store it back to price by using price = price + 7.50 (or price += 7.50)
Related
I am trying to write a function that gives a user 4 choices, does what they choose and then asks them the first 4 choices again and again until they exit.
I have tried using an if/else loop inside a while loop, but that just takes the first user input and loops at that point. It also concatenates the balance when I try to add the two numbers. I assume that due to the fact that the prompt is a string and assigns a string to the variable. I am using console.log() to try and see what is happening while everything is running, but to no avail.
Sorry if this is a lengthy post and redundant.
let balance = 0;
let deposit = 0;
let withdraw = 0;
function bankFunction (banked) {
alert('Hello, how can I help you today?');
let input = prompt('Q to quit the application \nW to withdraw \nD to deposit \nB to view balance');
while (input != 'Q') {
if (input === 'W') {
withdraw = prompt("Withdraw how much?");
console.log(withdraw);
balance = balance - withdraw;
console.log(balance);
} else if (input === 'D') {
deposit = prompt("Deposit how much?");
console.log(deposit);
balance = balance + withdraw;
console.log(balance);
} else {
alert("done");
break;
}
}
}
If you want to continuously prompt the user for inputs, then the prompt function should be inside your loop too. The essential pseudo code is: "While the input is not "Q", continue to prompt for a user choice".
Implementation:
let input = "A" // Initial input to get the loop working
while (input !== "Q") {
// Get actual user input
input = prompt("Choose Q or W or D or B");
if (input === "W") {
// Withdraw logic
}
else if (input === "D") {
// Deposit logic
} else if (input === "B") {
// ...
}
}
Note that there is a bit of a little gimmick here: I needed to have an initial input ("A") to get the first round of the loop working - since in the first round of the loop, user input has not been received yet. Once it get past that initial first round, the input variable is being continuously re-assigned through the user prompt, and the loop will exactly how the pseudo-code described it.
If you don't like that gimmick, there is another way, called the While-True-Break loop. The essential idea is that: The loop will automatically run forever, until you explicitly stop it (via break statement)
let input;
while (true) {
input = prompt("Choose Q or W or B or D");
if (input === "Q") {
// Stop the program loop
break;
} else if (input === "W") {
// ...
} else if ...
}
I'm trying to make a simple addition tool to add 2 values together, I'm just having a little trouble with the NaN checking... would like to print "Please insert numbers only" if either A or B, or both are NaN.
function getTotal() {
var a = parseInt(document.addBoxes.boxA.value);
var b = parseInt(document.addBoxes.boxB.value);
if (total != NaN) {
total = a+b;
document.getElementById("total").innerHTML = "The sum is " + total + ".";
}
else if (a === NaN || b === NaN){
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
else if (a === NaN && b === NaN){
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
};
Also, if there is a performance-friendly way to do this, or a better method.
Thanks!
Checking each individual value for NaN is not required.
function getTotal() {
var a = parseInt(document.addBoxes.boxA.value);
var b = parseInt(document.addBoxes.boxB.value);
var total = a + b;
if (!isNaN(total)) {
document.getElementById("total").innerHTML = "The sum is " + total + ".";
} else {
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
}
Several problems in your code.
Line 4: if (total != NaN) {
total hasn't been defined yet. You should define it in a var beforehand if you don't want to leak globals.
var total = a + b;
Also, NaN will never equal itself so this kind of equality is dangerous. Either use the built-in isNaN() function to check for NaN or (since you mentioned performance-friendly) you can skip the function invocation and use:
if (total !== total) {
Since NaN is the only thing in javascript that doesn't equal itself. Notice I'm using a strict not-equals, we don't want any coercion. This might be a bit too abstract and people who look at the code later (including yourself) might have forgotten this unique property of NaN so I'd prefix this conditional with a comment and perhaps a link to the MDN - Necessity of isNaN page.
Your code might end up looking something like simonzack's answer.
What is the best practice when counting the number of times an action has been carried out in javascript? for example I have a prompt that asks for a number
var playerGuess = prompt("What is your guess ");
What i would like to do is after 3 attempts end the game with another prompt.
What I am having difficulty with is actually counting the number of inputs
Thanks
I have tried creating a function do count the number of times an input has been made
var guessCount = playerGuess.count;
function limit(playerGuess){
if (guessCount >= 3){
alert("game over");
} else{
alert("carry on");
}
}
totally wrong i know but having a go
Like so:
// Global var to hold number of guesses
var guessCount = 0;
// Function to get the guess
function getGuess() {
// Get a new guess
var guess = prompt('What is your guess ');
// Process guess here, eg:
if (...whatever tests you want to make...) {
// Good guess
alert('Good guess: ' + guess);
} else {
// Bad guess
guessCount += 1;
// Fail out if too many guesses have been tried
if (guessCount >= 3) {
alert('Game over');
return;
}
}
};
Cheers!
You should evaluate the answer you get each time.
If the answer is valid, take the count in another variable and when the count reaches the desired amount take no inputs.
var attempts = 0;
function ask_question(){
if(attempts > 3)
{
// you have played enough!
return;
}
else
{
var playerGuess = prompt("What is your guess ");
if(parseInt(playerGuess) != NaN && playerGuess != '')
{
attempts++;
// do whatever you would like to do with playerGuess
}
}
}
You could do this with a while loop and a variable to store the current iteration. Consider the following, which gives you three chances to guess the "secret" number:
var secretNumber = 42,
youWon = false,
i = 0;
while (i < 3) {
var playerGuess = prompt("What is your guess?");
if (playerGuess == secretNumber){
youWon = true;
break;
}
i++;
}
if (youWon) {
alert("You got it!");
} else {
alert("Sorry, you have no more tries left.");
}
This code loops over and over, incrementing i each time. It asks the question, and checks the answer. If the answer is right, it sets the youWon flag and breaks out of the loop, ending it early. Otherwise, the loop ends naturally after 3 iterations. After the loop is done, the youWon flag is checked to determine if the loop ended because the right answer was given, or if it ended because the number of tries was exhausted.
as you can see in the picture, it would be silly for the user to have to type in all 5 Requested Brands (as that is not required). Maybe they only want to choose one Requested Brand. As it is currently set up, the subtotal is only calculated if the user enters 5 unit costs and 5 quantities...not good. If they don't enter all 5, subtotal returns NaN.
$("a#full_sub_total").click(function(event){
event.preventDefault();
var first = $("div#total_result").text();
var second = $("div#total_result1").text();
var third = $("div#total_result2").text();
var fourth = $("div#total_result3").text();
var fifth = $("div#total_result4").text();
$("#full_total_results p").text((parseInt(first,10) + parseInt(second,10) + parseInt(third,10) + parseInt(fourth,10) + parseInt(fifth,10)));
});
Any help is greatly appreciated.
I would loop over the total_result fields, and incrementally add their parsed values to a total var:
$("a#full_sub_total").on("click", function(){
var total = 0;
$("div[id^=total_result]").text(function(i,t){
total += parseInt( t, 10 ) || 0;
});
$(".full_total").text("$" + total);
});
Note the main part of all of this:
total += parseInt( t, 10 ) || 0;
When the attempt to parse an integer from the text of the element fails, we return 0 in its place. This will not offset the total value, and will permit us to continue along with out any NaN showing up later.
Demo: http://jsbin.com/axowew/2/edit
Basic technique:
var sum = 0;
var num1 = parseInt(text1, 10);
if (!isNaN(num1)) sum += num1;
// ...
(Loops: even better idea.)
The problem your overall total results in NaN is that anytime one or more of individual line total is empty, it will cause your overall result total to equal NaN in your attempt to add (i.e. #+#=#, #+NaN=Nan)
Simplify solution to your problem:
$('#subtotal').click(function(e) {
e.preventDefault();
// Clear overall total
$('#overallTotal').empty();
// Loop through each line total
$('div.lineTotal').each(function() {
// If line total is not empty, add
if ($(this).text() != ''){
$('#overallTotal').text(parseInt($('#overallTotal').text) += parseInt($(this).text()));
}
});
});
Hi I've been having so trouble with this project I need to change colors or matching numbers in 2 arrays, but have the remaining numbers stay there natural color.
for(d = 0; d < lotteryNums.length; d++) {
for(x = 0; x < quickDrawNums.length; x++) {
if(lotteryNums[d] == quickDrawNums[x]) {
quickDrawNums[x] = "<span class='winner'>" + quickDrawNums[x] + "</span>";
winCounter++;
} else {
quickDrawNums[x] = "<span class='number'>" + quickDrawNums[x] + "</span>";
}
}
}
When I have this display it gives me 5 empty boxes and 1 box with the number in it. It also stops my match if from working I was just wondering if anybody could help me sort this out. Thanks for the help in Advance :)
You need to remove the "else" because you are re-writing all the quickDrawNums every time the next lotteryNums is selected. This would result in only on class ='winner' on the last lotteryNums item. Not sure why the empty boxes appear. Verify the original "else" has correct spelling and case for objects, etc.