Hello I am trying to get this program to add ALL of the total costs that accumulate throughout this loop. But the program keeps printing the most recent cost rather than all of the products that have been "purchased". Here is my code: `
var Customer_Name, Discount, Product="", Price, Quantity="", Cost ;
var blanket_price = 25;
var lotion_price = 60;
var surfboard_price = 60;
var sunscreen_price = 60;
var Customer_Name = prompt("Welcome to Jersey Shore Inc.! What is your name?","Type Name Here");
alert("Hello "+Customer_Name+", Please look through all available products and services before placing your order.");
do
{
Product= prompt("What product would you like?","Type Product Name Here");
Quantity= prompt("How much of the "+Product+" would you like?","Type Quantity Here");
var Total_Cost;
var SumOrderTotal=0;
if (Product == "blanket")
{
alert("You received a 50% discount! Click okay to see your receipt below.");
Total_Cost= 0.5*(Quantity*blanket_price);
Cost=(Quantity*blanket_price);
Discount = .50*blanket_price;
}
else if (Product == "lotion")
{
alert("You received a 50% discount! Click okay to see your receipt below.");
Total_Cost= 0.5*(Quantity*lotion_price);
Cost=(Quantity*lotion_price);
Discount = .50*lotion_price;
}
else if (Product == "surfboard")
{
alert("You received a 50% discount!Click okay to see your receipt below.");
Total_Cost= 0.5*(Quantity*surfboard_price);
Cost=(Quantity*surfboard_price);
Discount = .50*surfboard_price;
}
else if (Product == "sunscreen")
{
alert("You received a 50% discount! Click okay to see your receipt below.");
Total_Cost= 0.5*(Quantity*sunscreen_price);
Cost=(Quantity*sunscreen_price);
Discount = .50*sunscreen_price;
}
if((Product=="blanket" || Product=="sunscreen" || Product=="lotion" || Product=="surfboard"))
{
document.write("The cost of buying " + Quantity+ " of " + Product + " is $ "+ Cost +". </br>");
document.write("The discount for this purchase is $ "+Total_Cost+". <br/>");
}
else
{
alert("Sorry "+Customer_Name+" you entered an invalid product.(Refer to table for our products) Please Refresh the page to reload and place a new order.");
}
var SumOrderTotal = Total_Cost + SumOrderTotal;
var user_answer=confirm("Would you like to continue purchasing products?");
}
while(user_answer==true);
document.write("Thank you for placing an order with us, " +Customer_Name+". <br/>");
document.write("Your total order cost is $"+ SumOrderTotal+ ". <br/>");
`
move SumOrderTotal outside of do...while.
Like so:
var SumOrderTotal=0;
do {
Product = prompt("...");
Quantity = prompt("...");
var Total_Cost;
} while (...) {
...
}
Because you are initializing to 0 each time you start the cycle(do..while).
Related
This is actually my first beginner project. I wrote the whole code myself. It's about buying phones through 3 different methods. You can tell the program to automatically buy all phones and phone masks for all money you got, to manually buy one by one or to enter a number of phones and masks you wanna buy. Together with all that I set a number of phones and masks available at the stop together with user's bank balance.
The problem's coming from eraseData function. It simply doesn't work. Actually, the first part of it works but the second where I'm trying to reset my variables to their original value isn't working.
I have problems with using this editor to put in my code so I will use Pastebin.
const PHONE_PRICE = 150.00;
const MASK_PRICE = 50;
var bankBalance = 1983;
var aPhones = 11;
var aMasks = 11;
var boughtPhones = 0;
var boughtMasks = 0;
function eraseData(){
var bankBalance = 1800;
var aPhones = 11;
var aMasks = 11;
var boughtPhones = 0;
var boughtMasks = 0;
var check = false;
var quantity = 0;
document.getElementById("money").innerHTML = "Money left: $" + bankBalance;
document.getElementById("phones").innerHTML = "Amount of phones: " + boughtPhones;
document.getElementById("masks").innerHTML = "Amount of phone masks: " + boughtMasks;
}
function updateData(){
document.getElementById("money").innerHTML = "Money left: $" + bankBalance;
document.getElementById("phones").innerHTML = "Amount of phones: " + boughtPhones;
document.getElementById("masks").innerHTML = "Amount of phone masks: " + boughtMasks;
}
checkOptions();
function checkOptions(){
var check = prompt("There is three different ways to buy a phone. (A)utomatically, (M)anually and by (Q)uantity. Choose one option.")
if(check == "A"){
buyPhoneA();
}
else if(check == "M"){
buyPhoneM();
}
else if(check == "Q"){
buyPhoneQ();
}
else{
alert("That's not a valid option!");
}
}
function buyPhoneA(){
alert("With this option you automatically spend all your money ($" + bankBalance.toFixed(2) + ") and buy all available phones and phone masks! (take in notice that you can't buy one if you don't have money for the other!)");
var check = prompt("Type I AGREE if you agree to use this option!");
if(check == "I AGREE" && aPhones >= 1 && aMasks >= 1 && bankBalance >= 200.00){
while(bankBalance >= PHONE_PRICE + MASK_PRICE){
aPhones--;
aMasks--;
boughtPhones++;
boughtMasks++;
bankBalance = bankBalance - PHONE_PRICE - MASK_PRICE;
updateData();
var check = false;
}
}
else{
alert("Something went wrong! Either you didn't type I AGREE correctly, we don't have phones left or you don't have enough money!");
console.log(aPhones + " phones left");
console.log(aMasks + " masks left!");
console.log(boughtMasks + " bought masks!");
console.log(boughtPhones + " bought phones!");
console.log(bankBalance + " money left in the bank");
checkOptions();
}
}
function buyPhoneM(){
alert("With this options we will ask your over and over again to buy a phone! You can decline or agree to buying a new one! No accessories included");
var check = prompt("Type I AGREE if you agree to do this option!");
if(check == "I AGREE" && bankBalance >= 150.00 && aPhones >= 1){
aPhones--;
boughtPhones++;
bankBalance = bankBalance - PHONE_PRICE;
updateData();
buyPhoneM();
var check = false;
}
else{
alert("Something went wrong! Either you didn't type I AGREE correctly, we don't have any phones left or you don't have enough money!");
checkOptions();
}
}
function buyPhoneQ(){
var quantity = 0;
alert("With this option you will be asked to input a number of phones and accessories you want to buy!");
var check = prompt("Type I AGREE if you agree to use this option!");
if(check == "I AGREE"){
var quantity = prompt("Input a number of how many phones and accessories you want to buy!")
if(bankBalance >= 200.00 && aPhones >= 1 && aMasks >= 1){
aPhones + aPhones - quantity;
aMasks = aMasks - quantity;
bankBalance = bankBalance - ((PHONE_PRICE + MASK_PRICE) * 2);
boughtPhones = boughtPhones + quantity;
boughtMasks = boughtMasks + quantity;
updateData();
var check = false;
}
else{
alert("Something went wrong! Either the message your typed is not a number, you don't have enough money, we don't have enough masks or phones!");
buyPhoneQ();
}
}
}
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<p id="money">Money left: $1800</p>
<p id="phones">Amount of phones: 0</p>
<p id="masks">Amount of phone masks: 0</p>
<br><br>
<button onclick="eraseData();">Erase Data</button>
<script type="text/javascript" src="script.js"></script>
</body>
CSS's not really important for this..
(I don't remember why exactly put script tags below my button tag but I think it's because of something weird happening with my code, it didn't work until I did it that way )
I'd be grateful if anyone could help, thanks!
You have used global variable and local variables name same.
Either rename the function variable different from global variables or remove var ahead of function variable.
I am new to using google Firebase. I have manage to add real time saving data function, but I wanted to save the data that i have. Please could someone direct me to the right path?
Here is the code in .JS file:
var btn = document.getElementById(btn);
var weight, height, measure, bmi, error ;
function calculate() {
var firebaseRef = firebase.database().ref();
firebaseRef.child("BMI").set("BMI Values");
weight = document.getElementById("weight").value;
height = document.getElementById("height").value;
error = "Please enter some values";
height /= 100;
height *= height;
bmi = weight/height;
bmi = bmi.toFixed(1);
if (bmi <= 18.4) {
measure = "Your BMI is " + bmi + " which means " + "you are Underweight";
} else if (bmi >= 18.5 && bmi <= 24.9) {
measure = "Your BMI is " + bmi + " which means " + "You are Normal";
} else if (bmi >= 25 && bmi <= 29.9) {
measure = "Your BMI is " + bmi + " which means " + "You are Overweight";
} else if (bmi >= 30) {
measure = "Your BMI is " + bmi + " which means " + "You are Obese";
}
if (weight === 0 ) {
document.getElementById("results").innerHTML = error;
} else if (height === 0){
document.getElementById("results").innerHTML = error;
}
else {
document.getElementById("results").innerHTML = measure;
}
if (weight < 0) {
document.getElementById("results").innerHTML = "Negative Values not Allowed";
}
}
To add the BMI data to the database, you do something like this:
weight = document.getElementById("weight").value;
height = document.getElementById("height").value;
error = "Please enter some values";
height /= 100;
height *= height;
bmi = weight/height;
bmi = bmi.toFixed(1);
firebaseRef.child("BMI").push({
weight: weight,
height: height,
bmi: bmi
});
Aside from (obviously) passing in the values you got from the HTML, this code calls push(), which generates a new unique location in the JSON every time it's called. That way the values you enter won't overwrite what's already there.
Note that HTML elements typically return value as a string. So you might still have to convert the weight and height to numbers after getting from the HTML element:
weight = parseFloat(document.getElementById("weight").value);
height = parseFloat(document.getElementById("height").value);
Finally: saving data to Firebase is pretty well covered in the Firebase documentation and in the Firebase codelab for web developers. I highly recommend you check those out. A few hours spent there, saves many questions down the line.
My problem is as followed: I want to realise a (really) small application in which I want to generate a letter (between A and E) and compare it with the user input made afterwards. If the user input is not the same as the generated letter a message should pop up, which tells the user that he made the wrong choice. If the user made the right choice, a counter gets +1 and if the user reaches at least 3 of 5 points, he wins a prize. The user has 3 tries before the script ends.
The hurdle is that my main focus lies on php. My knowledge in JavaScript is not that much.
So my script won't do anything when the user types his answer in.
SOLVED!
The Code beneath is the solution.
String.prototype.last = function(){
return this[this.length - 1]
}
;(function() {
var score = 0;
var text = "";
var possible = "ABCDE";
var noOfTries = 5;
function generateCharacter() {
var index = Math.floor(Math.random() * 100) % possible.length;
text = possible[index];
possible = possible.slice(0, index) + possible.slice(index+1);
alert(text);
return text;
}
function validate(string) {
return (string || "").trim().last() === text.last();
}
function handleChange(){
var valid = validate(this.value);
if(valid){
score++;
alert("Richtig!");
}else{
alert("Das war leider falsch. Die richtige Antwort wäre " + text + " gewesen!");
}
console.log(this.value.length === noOfTries)
this.value.length === noOfTries ? notify() : generateCharacter();
}
function notify(){
if(score == 0) {
alert("Schade! Sie haben " + score + " Punkte erreicht! Nochmal?");
}else if(score >= 1 && score <3){
alert("Schade! Sie haben lediglich " + score + " von 5 Punkten erreicht! Nochmal?");
}else if(score >= 3 && score <= 5) {
alert("Herzlichen Glückwunsch! Sie haben " + score + " von 5 Punkten erreicht!");
}
}
function registerEvent(){
document.getElementById('which').addEventListener('keyup', handleChange);
}
registerEvent();
generateCharacter();
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="which">Antwort? </label>
<input type="text" name="which" id="which" placeholder="#" style="width: 9px;">
And here's the fiddle: Compare generated string with user input
I am writing a number guessing game. Every time I run the document it automatically goes to my outer else statement and I know why, but I can't figure out how to make it wait for an input value of the textbox. I want to set "guess" = to the value of the text box by pressing submit which will then enter the if statements. At the moment it is automatically setting to null and causing the error. Here is the code.
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Number Guessing Game</h1><br>
<button onclick = "search(1,100)">Press to play!</button>
</body>
<script type="text/javascript">
var counter = 0;
var randomNumber = Math.floor(Math.random()*100+1);
function search(first, last){
document.open();
document.write("<h1>Number Guessing Game</h1><br>");
document.write("<input id = 'guessBox' type = 'text'> ");
document.write("<input type = 'submit' id = 'submit' value = 'Submit'><br>");
document.write("<h2>Numbers Left</h2>");
for(var i = first; i <= last; i++){
document.write(i + " ");
}
document.write("<br><br><h3>Number of tries: " + counter + "</h3>");
document.close();
var guess = document.getElementById('guessBox').value;
//var guess = prompt("Guess!");
myguess = parseInt(guess);
if(myguess <= last && myguess >= first && cont == true){
if(myguess == randomNumber){
counter++;
if(counter <=3){
alert("WOW, that was amazingly quick! You found it in " + counter + " tries.");
}
else if(counter < 6 && counter >= 4){
alert("Not bad! You found it in " + counter + " tries.");
}
else if(counter < 10 && counter >= 6){
alert("Ouch! You found it in " + counter + " tries.");
}
else{
alert("Having a bad day aren't you? You found it in "+ counter + " tries");
}
}
else if(myguess < randomNumber){
first = myguess+1;
alert("Try again! The number is higher.");
counter++;
search(first, last);
}
else{
last = myguess-1;
alert("Try again! The number is lower.");
counter++;
search(first, last);
}
}
else{
alert("Invalid Number, try again.");
search(first, last);
}
}
</script>
Have you tried to disable the button, then add an onChange event to your text box so that you can enable the button once you have the desired input? You will need to add an ID or Name value to your button so it can be accessed? And to add what #LGSon added:
if(myguess <= last && myguess >= first && cont == true){, you check the variable cont, which I can't find in your code, so if it is not declared and set somewhere, you code will always take the outer route.
Second, you need to split your search function into 2 functions, one that generates the input, one that runs when someone entered a value (which can be fired on keypress or with a button)
I want to be able to have a form that takes a 'deposit' or 'withdraw' and will add or subtract for a variable. Then, I would like to be able to put that variable in the webpage, and be able to keep it for a day or two. I do not know what is wrong with my code at this point.
<html>
<head>
<script language="JavaScript">
<!-- hide this script from old browsers
//Bank
var bank = 0;
var bank_name = "The Bank of Pacycephalosaurus";
var bank_interestPolicy = 0;
var bank_interestPolicy_interestAmount = 2;
var bank_ineterestPolicy_interest = function (amount) {
var interestGain = bank_contents_money / bank_interestPolicy_interestAmount;
var bank_contents_money = bank_contents_money + interestGain;
};
var bank_contents = 0;
var bank_contents_money = 0;
var bank_contents_items = "None";
var bank_withdrawAmount = "0";
var bank_depositAmount = "0";
var bank_withdraw = function (amount) {
//Check if there is money
if (bank_contents_money < amount) {
alert("Withdraw DENIED Insufficient Funds");
} else {
alert("Sufficient Funds ... Transfering Funds ...");
var transPlace = confirm("Transfer funds to " + wallet_name + "?");
if (transPlace === false) {
alert("Transfer Location Unknown :: 404 Not Found :: Please Try Again");
} else {
alert("Transfering Funds ... Transfer Succesful!");
form.bank_money.value = bank_contents_money - amount;
wallet_money = wallet_money + amount;
}
}
};
var bank_deposit = function (amount) {
//Check if there is money
if (wallet_money < amount) {
alert("Deposit DENIED Insufficient Funds");
} else {
alert("Sufficient Funds ... Transfering Funds ...");
var transPlace = confirm("Transfer funds to " + bank_name + "?");
if (transPlace === false) {
alert("Transfer Location Unknown :: 404 Not Found :: Please Try Again");
} else {
alert("Transfering Funds ... Transfer Succesful!");
alert("The Amount: " + amount);
form.bank_money.value = bank.contents_money + amount;
bank_contents_money = bank.contents_money + amount;
alert("The Amount: " + amount);
bank_opening(amount);
}
}
};
var bank_opening = function (money) {
alert("You have $" + bank_contents_money + " in your bank.");
$.cookie("bankMoney", money, {
expires: 1
});
alert($.cookie("example"));
};
var wallet = 0;
var wallet_name = "Wallet of You!";
var wallet_money = 0;
bank_opening();
// done hiding from old browsers -->
</script>
</head>
<body>
<form>
<h2>Bamk</h2>
Enter a number to withdraw or deposit:
<INPUT NAME="deposit" VALUE="0" MAXLENGTH="15" SIZE=15>
<p>
<INPUT NAME="depos" VALUE="Deposit" TYPE=BUTTON
onClick=bank_deposit(deposit.form)>
<p>
<p>
<INPUT NAME="withd" VALUE="Withdraw" TYPE=BUTTON
onClick=bank_withdraw(this.form)>
<p>
The amount in a bank is:
<INPUT NAME="bank_contents_money" READONLY SIZE=15>
</form>
</body>
</html>