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.
Related
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'm working on what should be an extremely simple "guess my number" game in Javascript, however, I can't get it to work correctly.
The program is supposed to choose a random integer between 1 and 10 and allow the user to try and guess that number as many times as it takes to get it right. If the user guesses a number that's lower than the correct one, the program is supposed to display a "your guess is too low" message, this is the same for when the guess is too high, or correct. The program must display the message on the webpage, not in an alert or any type of pop-up. Also, the program is supposed to keep a running list of the numbers that have been guessed by the user and display them on the page each time the user makes a guess (I want this list to display below my heading "Here are the numbers you've guessed so far:"). And finally, the program is supposed to display a "you already tried using that number" message if the user tries to input a number that they've already used.
Here is my code, along with a JSfiddle I've created and am still playing with.
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Guess My Number</title>
<script type = "text/javascript">
var tries = [];
game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum : function() {
this.num = parseInt(Math.random(), 10) + 1;
},
guessNumber : function(guess) {
try {
guess = parseInt(guess, 10);
}
catch (e) {
document.getElementById("guess").value = "Enter a guess.";
this.turns++;
return false;
}
if (guess == this.num) {
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return true;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
tries.push(document.getElementById("guess").value;
display();
document.getElementById("guess").value = " ";
return false;
}
else if(tries.indexOf(guess) != -1 {
document.getElementById("result").value = "You have already guessed that number. Try again.";
document.getElementById("guess").value = " ";
return false;
}
else {
document.getElementById("result").value = "Your guess is too low. Try again.";
tries.push(document.getElementById("guess").value;
display();
document.getElementById("guess").value = " ";
return false;
}
}
function display() {
var number = ";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
resetGame();
}
</script>
</head>
<body>
<h1>Would You Like To Play A Game?</h1>
<h3>Directions:</h3>
<p>
The game is very simple. I am thinking of a non-decimal number between 1 and 10, it is your job to guess what that number is. If you guess incorrectly on your first attempt, don't worry. You can keep guessing until you guess my number.
</p>
<h3>Thanks for playing and good luck!</h3>
<h3>Created by Beth Tanner</h3>
<p>Your Guess:
<input type = "text" id = "guess" size = "10" />
<br />
<input type = "button" value = "Submit Guess" onclick = "guessNumber()" onclick = "display()" />
<input type = "reset" value = "Reset Game" onclick = "resetGame()" />
</p>
<h3>How'd you do?</h3>
<div id = "result">
<input type = "text" id = "result" size = "20" />
</div>
<h3>Here are the numbers you've guessed so far:</h3>
</body>
</html>
http://jsfiddle.net/v09ttL74/
As you should be able to see from the fiddle, nothing is happening when I click either one of the buttons, so I'm not really sure where the problem is. I am getting a few errors when I select the JShints option on the fiddle, but most are things like "Missing semicolon" in places where there's not supposed to be a semicolon, like an one line where all I have written is
else {
Any suggestions would be greatly appreciated. I feel like this is just a really simple project that I am over-thinking since I'm stressed about it not working.
There's a lot of issues in your code. Just to mention a few...
1- Unclosed parenthesis here
tries.push(document.getElementById("guess").value;
it should be...
tries.push(document.getElementById("guess").value);
2- Expression not terminated with a close parenthesis here
else if(tries.indexOf(guess) != -1 {
it should be...
else if(tries.indexOf(guess) != -1) {
3- Wrong declaration of functions inside a function
function display() {
var number = ";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
I could be going forever but, really, the errors are a bit obvious
Alright as some of the answers must have already given you an idea of how many mistakes your Script as well as HTML code had.. from missing parenthesis to same ids to missing elements. Well i have corrected them and it's working now:
<h1>Would You Like To Play A Game?</h1>
<h3>Directions:</h3>
<p>
The game is very simple. I am thinking of a non-decimal number between 1 and 10, it is your job to guess what that number is. If you guess incorrectly on your first attempt, don't worry. You can keep guessing until you guess my number.
</p>
<h3>Thanks for playing and good luck!</h3>
<h3>Created by Beth Tanner</h3>
<p>Your Guess:
<input type = "text" id = "guess" size = "10" />
<br />
<input type = "button" value = "Submit Guess" onclick = "guessNumber()" onclick = "display()" />
<input type = "reset" value = "Reset Game" onclick = "resetGame()" />
</p>
<h3>How'd you do?</h3>
<input type = "text" id = "result" size = "20" />
<h3>Here are the numbers you've guessed so far:</h3>
<p id='tries'></p>
Script:
var tries = [];
game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum : function() {
this.num = parseInt(Math.random() * 10) + 1;
},
guessNumber : function(guess) {
try {
guess = parseInt(guess, 10);
}
catch (e) {
document.getElementById("guess").value = "Enter a guess.";
this.turns++;
return false;
}
alert(guess+ ' '+this.num);
if (guess == this.num) {
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return true;
}
else if(tries.indexOf(guess) != -1) {
document.getElementById("result").value = "You have already guessed that number. Try again.";
document.getElementById("guess").value = " ";
return false;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return false;
}
else if(guess < this.num){
document.getElementById("result").value = "Your guess is too low. Try again.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return false;
}
}
}
function display() {
var number = "";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
resetGame();
See the DEMO here
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).
I'm brand new to javascript and html so I was hoping someone could peek at my code and tell me why certain syntax isn't working. In the code below I use document.getElementById to retreive the element I'd like to work with each time. I do declare them as local variables within gameTime() and use it throughout the function.
var randNum = Math.floor( 100*Math.random() ) +1;
var numGuesses = 0;
function gameTime()
{
var guess = document.getElementById("guess").value;
var status = document.getElementById("status");
numGuesses++;
if(guess == "")
{
alert("You did not guess a number!")
numGuesses--;
}
else if(guess == randNum)
status.value += (guess + " was the right number! It only took you " + numGuesses + " tries" + "\r")
else if(guess > randNum)
status.value += (guess + " is too high!" + "\r")
else
status.value += (guess + " is too low!" + "\r")
document.getElementById("guess").value = "";
}
function reset()
{
randNum = Math.floor( 100*Math.random() ) +1;
numGuesses = 0;
document.getElementById("guess").value = "";
document.getElementById("status").value = "";
}
function quit()
{
document.getElementById("status").value += ("The correct number was " + randNum + "!\r")
}
Then I tried it by globally declaring the two elements and use it in every function which does not seem to work at all and I just don't understand why.
var randNum = Math.floor( 100*Math.random() ) +1;
var numGuesses = 0;
var guess = document.getElementById("guess").value;
var status = document.getElementById("status");
function gameTime()
{
numGuesses++;
if(guess == "")
{
alert("You did not guess a number!")
numGuesses--;
}
else if(guess == randNum)
status.value += (guess + " was the right number! It only took you " + numGuesses + " tries" + "\r")
else if(guess > randNum)
status.value += (guess + " is too high!" + "\r")
else
status.value += (guess + " is too low!" + "\r")
guess.value = "";
}
function reset()
{
randNum = Math.floor( 100*Math.random() ) +1;
numGuesses = 0;
guess.value = "";
status.value = "";
}
function quit()
{
status.value += ("The correct number was " + randNum + "!\r")
}
And here's the html file that accompanies these js files guess.js is the first code block, guessAgain.js is the second code block.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guessing Game</title>
<script type="text/javascript" src="guessAgain.js"></script>
</head>
<body>
<label for = "guess"> Your Guess: </label>
<input type = "text" id = "guess" value = "" />
<input type = "button" onclick = "gameTime()" value = "Submit" />
<input type = "button" onclick = "reset()" value = "New Game" />
<input type = "button" onclick = "quit()" value = "Quit" />
<br>
<textarea id = "status" rows = "10" cols = "52"></textarea>
</body>
</html>
Thanks for any insight you can give me.
Issue 1:
You are calling the following before the body loads and hence, they return undefined.
var guess = document.getElementById("guess");
var status = document.getElementById("status");
You should do these only after the body loads on the onload() event.
Issue 2:
Also, when you assign the value itself to a variable, it isn't updated as the textbox is. var guess = document.getElementById("guess").value, then guess's value does not get updated if you change the textbox.
If you refer to var guess = document.getElementById("guess"), then, repeatedly calling
guess.value will return the latest value of the input field.
(Working Example)
The following is not wrong by unnecessarily complicated.
numGuesses++;
if(guess.value == "")
{
alert("You did not guess a number!")
numGuesses--;
}
...
Instead, you could increment numGuesses once it is deemed a valid guess, i.e. at the end.
You're setting guess to element.value
It should be
var guess = document.getElementById("guess");
Problem is that you're using guess as an element here:
guess.value = "";
You'll also need to modify places where you use guess as a string into guess.value.