I tried to create a Html / Js money counter but if i update, it updates one tick and then it resets itself to an old value. I tried creating a function named update and let it run every time the money value changes, but that did not work either.
<html>
<head>
<title>Betting Simulator Test!</title>
</head>
<body>
<br/>
<p id="p1">You have 500$</p>
<br/>
<form name="CoinFlip" action="" onsubmit="Create()" method="post">
Coins: <input type="text" name="Csubmit">
<input type="submit" value="Flip the Coin">
</form>
<script type="text/javascript">
Balance = 500;
function Game() {
if(Balance >= 1) {
var Coin = confirm("You have put " + sub + "$ in the CoinFlip!");
if(Coin == true) {
var flip = true
if(flip == true) {
alert("You won " + sub + "$");
Balance = Balance + sub*2 - sub;
Update = document.getElementById("p1").textContent="You have " + Balance + "$";
} else {
alert("You lost " + sub + "$");
Balance = Balance - sub;
Update = document.getElementById("p1").textContent="You have " + Balance + "$";
}
} else {
}
} else {
alert("You ran out of Money");
}
}
function Create() {
sub = document.forms["CoinFlip"]["Csubmit"].value;
if(sub <= Balance && sub > 0) {
Game();
} else {
alert("value does not make any sense!");
}
}
</script>
</body>
You have multiple problems. The first one is that you submit a form each time you play, so the page refreshes, and everything is lost. You could find a workaround to avoid this (see this), but in this case, a form is really not needed.
Also, the user is always going to win because you always set flip to true. You can simulate a random win by using this snippet:
var win = Math.round( Math.random() ); // 1 or 0 (truthy or falsy)
Here is a working example:
var balance = 500;
document.getElementById('flip').addEventListener('click', play);
function play(){
// parseInt() converts a String to an integer (10 is for decimal base)
var bet = parseInt(document.getElementById('bet').value, 10);
if(bet <= balance && bet > 0)
{
var accepted = confirm("Do you really want to bet " + bet + "$?");
if(accepted)
{
var win = Math.round( Math.random() ); // Random win
if(win)
{
alert("You won " + bet + "$!");
balance += bet;
}
else
{
alert("You lost " + bet + "$...");
balance -= bet;
}
if(!balance){ alert('You ran out of money...'); }
document.getElementById('p1').textContent = "You have " + balance + "$";
}
document.getElementById('bet').value = 0;
}
else
{
alert("Your bet makes no sense!");
}
}
<p id="p1">You have 500$</p>
<p>Coins: <input type="number" value="0" id="bet"> <button id="flip">Flip the coin</button>
Related
I'm fairly new to JavaScript, but I have some experience in other languages. I've been working on making my own small project, and I'm still figuring out how some things work. I have two problems that I need help solving. The first one, is that I have a button that should appear after you get 100 points, and click the button. This is at the if (buyupgrade == 1) and the following parts of that. I want the button to appear after the conditions are met (buy the first upgrade after getting 100 points). I also want to be printing the text part of a button, but in the text, I need it to display a variable, So my button text will display some words and a variable. Thanks for the help!
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost 200</button>
<script>
var points = 98;
var pointMulti = 1;
var buyupgrade = 0;
var currentpoints = setInterval(pointupdate, 1000);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + points + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
}
if (buyupgrade == 1) {
document.getElementById("firstbuild");
firstbuild.style.display = "inline";
function build1() {
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + points + " points!";
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
</body>
</html>
Your code that is supposed to make the third button visible is by itself outside any function. This seems like a typo:
if (buyupgrade == 1) {
document.getElementById("firstbuild");
firstbuild.style.display = "inline";
function build1() {
}
This only gets called the first time through the program when buyupgrade == 0
I think you meant for this to be inside the function:
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
// add some text to the button
firstbuild.innerText = "buyupgrade: " + buyupgrade
}
}
Also, there's a typo:
document.getElementById("firstbuild");
should probably be:
var firstbuild = document.getElementById("firstbuild");
EDIT: the issue was a typo, this should have been caught and is not a good question. Sorry about that
So I've been working on making one of my own projects in JS, and it involves lots of buttons. I have one button (The one with the ID of "firstbuildmulti1") which should run the function "build1multi1" But I don't think it is doing that. I've looked over it multiple times and I'm not sure why it won't work. Any help is appreciated! (Side note: the button only appears after you click the third building button, this is intentional). EDIT: I ran the code on here and it said:
{
"message": "Uncaught ReferenceError: b1m1cost is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 183,
"colno": 17
}
My code is:
//declare variables for points, multiplier, buy upgrade, b1 2 and 3 cost and count, make point updater
var points = 9999;
var pointMulti = 1;
var buyupgrade = 0;
var b1cost = 200;
var b1count = 0;
var b2cost = 1000;
var b2count = 0;
var b3cost = 2000;
var b3count = 0;
var b1m1cost = 1500;
var currentpoints = setInterval(pointupdate, 500);
//clicking on main button to add points
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + Math.round(points) + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
console.log();
}
}
//make logic for doubling addpoints
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti;
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
//logic for displaying first building upgrade
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
firstbuild.innerText = "Building 1. Cost " + b1cost;
var show2ndx2 = document.getElementById("secondx2");
multiply2.style.display = "inline";
}
}
}
//displays total points
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + Math.round(points) + " points!";
}
//what happens when you click first building button
function build1() {
if (points >= b1cost) {
points -= b1cost;
b1count++;
b1cost *= 1.10;
var b1multi = 1;
var b1pps = b1count * b1multi;
document.getElementById("b1").innerHTML = "You have " + b1count + " of building 1! Making " + b1pps + " points per second."
firstbuild.innerText = "Building 1. Cost " + Math.round(b1cost);
var build1add = setInterval(build1points, 1000);
//display second building
var secondbuild = document.getElementById("secondbuild");
secondbuild.style.display = "inline";
secondbuild.innerText = "Building 2. Cost " + b2cost;
}
}
//what happens when you click second building button
function build2() {
if (points >= b2cost) {
points -= b2cost;
b2count++;
b2cost *= 1.10;
var b2multi = 1;
var b2pps = (b2count * 4) * b2multi;
document.getElementById("b2").innerHTML = "You have " + b2count + " of building 2! Making " + b2pps + " points per second."
secondbuild.innerText = "Building 2. Cost " + Math.round(b2cost);
var build2add = setInterval(build2points, 1000);
//display third building
var thirdbuild = document.getElementById("thirdbuild");
thirdbuild.style.display = "inline";
thirdbuild.innerText = "Building 3. Cost " + b3cost;
}
}
//what happens when you click third building button
function build3() {
if (points >= b3cost) {
points -= b3cost;
b3count++;
b3cost *= 1.10;
var b3multi = 1;
var b3pps = (b3count * 10) * b3multi;
document.getElementById("b3").innerHTML = "You have " + b3count + " of building 3! Making " + b3pps + " points per second."
thirdbuild.innerText = "Building 3. Cost " + Math.round(b3cost);
var build3add = setInterval(build3points, 1000);
//first building first multiplier
var firstbuildmulti1 = document.getElementById("firstbuildmulti1");
firstbuildmulti1.style.display = "inline";
firstbuildmulti1.innerText = "Building 1 x2 multiplier. Cost: " + b1m1cost + "."
}
}
//add points for build1
function build1points() {
points += 1;
}
//add points for build2
function build2points() {
points += 4;
}
//add points for build3
function build3points() {
points += 10;
}
//second x2, display multiplier
function secondx2() {
if (buyupgrade == 1 && points >= 1000) {
pointMulti *= 2;
points -= 1000;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti;
multiply2.style.display = "none";
}
}
function build1multi1() {
if (points >= b1m1cost) {
points -= b1m1cost;
b1multi *= 2;
var build1multi1 = document.getElementById("build1multi1");
build1multi1.style.display = "none";
}
}
<p>Click to get started!</p>
<!--Link to all CSS files -->
<link rel="stylesheet" href="buttons.css">
<link rel="stylesheet" href="displayscores.css">
<link rel="stylesheet" href="layout.css">
<!-- make all buttons -->
<button id="addpoints" onclick="addPoints()" background-color:red>Add points</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost x</button>
<button id="secondbuild" onclick="build2()" style="display:none;">Building 2. Cost x</button>
<button id="thirdbuild" onclick="build3()" style="display:none;">Building 3. Cost x</button>
<br>
<p><b>Upgrades:</b></p>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="multiply2" onclick="secondx2()" style="display:none;">x2 Multiplier. Cost: 1000</button>
<button id="firstbuildmulti1" onclick="build1multi1()" style="display:none;">Building 1 x2 multiplier. Cost x</button>
<!-- make a div around all paragraphs displaying stats and display them -->
<div class="displayscores">
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
<p id="b1"></p>
<p id="b2"></p>
<p id="b3"></p>
</div>
First things first, as discussed in the comments, anytime you're stuck with the code, you can try using console.log() (If you're new to it, research a bit on using the Console for debugging)
function build1multi1() {
console.log("Entered function"); //If this is printed in console, that means the function is called
if (points >= b1m1cost) {
console.log("Entered condition"); //If this is not printed in console, it means condition points >= b1m1cost fails.
// console.log(b1m1cost); // You can check b1m1cost value in the console
// console.log(points); // You can check points value in the console
points -= b1m1cost;
b1multi *= 2;
var build1multi1 = document.getElementById("build1multi1");
build1multi1.style.display = "none";
}
}
Problem 1 : b1m1cost is not defined
b1m1cost is not defined in the global scope. It is only declared in one of the functions. Hence, the condition inside build1multi1() must be failing.
Problem 2 : Can't read property style of null (Doesn't hide the button)
This is happening inside the build1multi1() function.
Which means var build1multi1 inside that function is null.
Which means document.getElementById("build1multi1"); is unable to find any element with id build1multi1.
If you want to hide the button then the id should be firstbuildmulti1 which is the id for the button. So, change it to document.getElementById("firstbuildmulti1");
I have a basic hangman program. Click on the letter, it then tells you if its right or wrong by coloring the letter red or green. If its green, it replaces a dash in the hidden word with the letter. That part of my code works. The part that doesn't work is that I have an output section to a div that is supposed to tell you if you got the guess correct or not, and upon 6 failed guesses, you lose and it resets. It's currently not doing any of that. It's not even displaying anything in the div at all.
TY ahead of time. If you have questions about something I didn't explain well enough, ill be back in about 1 hour to answer them. Thanks!
Jsfiddle - http://jsfiddle.net/25b3fr4u/
HTML -
<body>
<form id="form" name="form" method="post" action="">
<input type="button" id="but" value="Start"/>
<div id="hangman-jquery">
<div id="word"></div>
<div id="alpha"></div>
</div>
</form>
<div id="win">
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="hangman.js"></script>
</body>
JS -
function hangman(word) {
var trys = 0;
var guess = 0;
var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$.each(alpha.split(''), function(i, val) {
$('#alpha').append($('<span class="guess">' + val + '</span>'));
});
$.each(word.split(''), function(i, val) {
$('#word').append($('<span class="letter" letter="' + val + '">-</span>'));
});
$('.guess').click(function() {
var count = $('#word [letter=' + $(this).text() + ']').each(function() {
$(this).text($(this).attr('letter'));
}).length;
$(this).removeClass('guess').css('color', (count > 0 ? 'green' : 'red')).unbind('click');
if (guess > 0) {
$('#win').text("Correct Guess");
} else if (guess < 0) {
$(this).html(++trys);
$('#win').text("You have tried to guess the word and failed " + trys + " times");
}
if (trys == 6) {
alert("You have guessed six times, you lose");
trys = 0;
$("#win").text("");
}
});
}
$(document).ready(function() {
$('#but').click(function() {
var options = new Array("DOG", "CAT", "BAT", "HORSE", "TIGER", "LION", "BEAR", "LIGER", "DOOM", "SPIDER", "TREES", "LAPTOP");
var random = 1 + Math.floor(Math.random() * 12);
hangman(options[random]);
});
});
Code fixed :http://jsfiddle.net/25b3fr4u/1/. The trys where not incremeted properly and you have to check the count instead of guess in your condition. guess was set to 0 and never use.
var count = $('#word [letter=' + $(this).text() + ']').each(function() {
$(this).text($(this).attr('letter'));
}).length;
$(this).removeClass('guess').css('color', (count > 0 ? 'green' : 'red')).unbind('click');
if (count > 0) {
$('#win').text("Correct Guess");
} else if (!count > 0) {
trys++;
$('#win').text("You have tried to guess the word and failed " + trys + " times");
}
if (trys == 6) {
alert("You have guessed six times, you lose");
trys = 0;
$("#win").text("");
}
I'm sure you can handle the rest. Have fun.
I'm making an app that compares a randomly generated number to a number input by the user. From there the app guides the user via "hotter" and "colder" prompts. I'm close, but right now my issue is that the prompts disappear after being displayed for about 1 second. I want the "hotter" or "colder" prompt to stay visible until the user inputs another number.
Here is a link to the app: http://dl.dropboxusercontent.com/u/91499081/HotOrCold/HotOrCold.html?guess=&submit=Submit
Here is my javascript code:
$(document).ready(function () {
var answer = Math.floor((Math.random() * 100) + 1);
console.log("The secret number is: " + answer);
var numberOfGuesses = 0;
var guesses = [];
var distance = null;
var previousDistance = null;
function getGuess() {
$("#submit").click(game);
$("#guess").keydown(function (enter) {
if (enter.keyCode == 13) {
game();
}
});
}
getGuess();
function game() {
var guess = parseInt($('#guess').val());
if (guess !== null && $.isNumeric(guess) && (1 < guess < 101)) {
$('#guess').val('');
numberOfGuesses += 1;
guesses.push(guess);
distance = Math.abs(answer - guess);
previousDistance = Math.abs(answer - guesses[guesses.length - 2]);
if (guess === answer) {
$('#hint').html('Congrats! You got it in ' + numberOfGuesses + ' attempts! The secret number was ' + answer);
} else {
console.log(guess, answer, previousDistance, distance);
if (isNaN(previousDistance)) {
if (guess > answer) {
$('#hint').html('Guess lower! Last guess: ' + guess);
} else if (guess < answer) {
$('#hint').html('Guess higher! Last guess: ' + guess);
}
} else if (distance > previousDistance) {
if (guess > answer) {
$('#hint').html('You\'re getting colder, guess lower! Last guess: ' + guess);
} else if (guess < answer) {
$('#hint').html('You\'re getting colder, guess higher! Last guess: ' + guess);
}
} else if (distance < previousDistance) {
if (guess > answer) {
$('#hint').html('You\'re getting hotter, guess lower! Last guess: ' + guess);
} else if (guess < answer) {
$('#hint').html('You\'re getting hotter, guess higher! Last guess: ' + guess);
}
} else if (distance === previousDistance) {
if (guess > answer) {
$('#hint').html('You\'re on fire, guess lower! Last guess: ' + guess);
} else if (guess < answer) {
$('#hint').html('You\'re on fire, guess higher! Last guess: ' + guess);
}
} else {
$('#hint').html('ERROR: Your guess must be a number between 1 and 100').css({
color: 'red'
});
}
}
}
$('#newgame').click(function (e) {
e.preventDefault();
answer = Math.floor((Math.random() * 100) + 1);
console.log(answer);
numberOfGuesses = 0;
guesses = [];
distance = null;
previousDistance = null;
$('#hint').html('');
$('#guess').val('');
});
}
});
The actual issue is in your HTML. You have a submit button that is part of a form. When you click submit, it is looking for a form action which isn't specified so it is reloading the page.
Change your <form> tag to keep you on the same page by changing it from this:
<form id="myform">
to this:
<form id="myform" action="#">
Or even better, make it so the JS function returns false so that the submit won't go through.
Don't use a <input type="submit" /> button. When it's clicked, your form will attempt to fire off whatever is in the action attribute, which is reloading your page.
You have many options.
I would just use <input type="button" /> or Submit. Then fire off the event when the button or link is clicked.
Your form performs its normal behaviour: post its data to the server. You need to disabled that action. You can either change your 'submit' button to be a normal button so it won't behave as submit:
<input type="button" name="submit" id="submit" class="button"/>
Or add a onsubmit to your form:
<form id="myform" onsubmit="return false">.
Your form is submitting regularly. Since you do not have any action attribute in your form, it will submit your form to the current page. What you want, is to handle the submit with javascript:
<form id="myform">
and in your javascript:
$('#myform').on('submit', game);
function game(event) {
// your code goes here
event.preventDefault();
}
in this way also enter will trigger a post which is handled by javascript, instead of only clicking a submit button.
I've been learning HTML/CSS/JavaScript for a couple of weeks now, and I am currently practicing on a mini project, which consists of letting people answer math questions, and validating their answers.
My current progress can be seen at http://dany.faceflow.com
I know I am probably not using the best strategy to develop this mini game, so any advice would be useful on that. However right now, the problem is that I am taking the user answer with a variable through JS prompt, and I want to do it via an HTML form (less annoying).
In my source code you can see this line within the function:
var userInput = prompt(numb1 + symbol + numb2);
Then, still in the same function, I have an if/else structure to compare the user's answer with the right answer. The code works, I just don't know how to make the prompt HTML-based instead. I've tried an html form with an ID and in the JS using getElementById, document.write and some other stuff but I never got it to work for that part.
(Here's all the JS)
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
var userAnswer = function() {
var numb1 = number1();
var numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
// Prompts the user to give an answer. Change this to HTML.
var userInput = prompt(numb1 + symbol + numb2);
//var userInput = document.getElementById('tw').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
return userInput;
}
(The HTML)
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<script src="js/script.js"></script>
<title>Improve Your Math Skills!</title>
</head>
<body>
<center>
<button onclick="userAnswer()">PLAY NOW!</button>
<div id="bubble"></div>
<div id="feedback"></div>
<!-- <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> -->
</center>
</body>
</html>
Thank you
You can use an input tag instead of the prompt. Change the HTML just as in Dinesh's answer;
<div id="bubble"></div>
<div id="inp" style="display: none;">
<input type="text" id="ans"></input> <button id="subBtn">Submit</button>
</div>
<div id="feedback"></div>
Now, for the JavaScript, there a few things to consider. Firstly, you have
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
Both functions do exactly the same thing; you don't need two separate functions to get two separate random numbers. So, only one function will suffice.
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
Secondly, now we have two functions. userAnswer to post a new question when 'Play Now!' is clicked and, say, evalAnswer to evaluate the answer written in the input field when 'Submit' is clicked.
In userAnswer, you generate two new random numbers and figure out which operation will be conducted on them. At this point, you can simply evaluate the answer yourself and store it in a global variable. This makes things easier when you evaluate the answer, you only need to do a simple comparison.
Other than that, you update innerHTML for bubble and display the div inp.
In evalAnswer, you get the value from ans and compare it with the previously computed value of the current answer, and then accordingly update feedback.innerHTML.
Here's the code;
//variable to maintain the current answer
var curAns = 0;
//Here, I get all the DOMElements I will use
var playBtn = document.getElementById('playBtn');
var bubble = document.getElementById('bubble');
var inp = document.getElementById('inp');
var ans = document.getElementById('ans');
var subBtn = document.getElementById('subBtn');
var feedback = document.getElementById('feedback');
//I add the event listeners
//This is equivalent to using 'onclick'
//in the HTML, and doing it this way is only
//my personal preference
playBtn.addEventListener('click', function() {userAnswer();}, false);
subBtn.addEventListener('click', function() {evalAnswer();}, false);
//Function to get random number
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
//This function will be executed when 'Play Now!' is clicked.
var userAnswer = function() {
//Get two separate random numbers in
//numb1 and numb2
var numb1 = number();
var numb2 = number();
var symbol = '';
var randomSymbol = Math.random();
//Determine the operation to be used
//and compute the corresponding correct answer for the current
//question
if (randomSymbol > 0.5) {
symbol = "+";
curAns = numb1+numb2;
} else {
symbol = "-";
curAns = numb1-numb2;
}
//Add math question to bubble
bubble.innerHTML = 'What is ' + numb1 + ' ' + symbol + ' ' + numb2 + '?';
feedback.innerHTML = '';
//Make inp div visible
inp.style.display = 'block';
//Reset input value to ''
ans.value = '';
};
//This function will be executed when 'Submit' is clicked
var evalAnswer = function() {
//Simply compare input value with computed
//answer and update feedback
if(parseInt(ans.value) !== curAns) {
feedback.innerHTML = 'Wrong answer, try again!';
}
else {
feedback.innerHTML = 'You got it right, congratulations!';
}
};
Here's a working example.
Hope that helped!
What I understand from your question is that you need the same functionality in HTML itself rather than driven by JS in a prompt box, if so,the below additions to your code should help:
HTML adition:
<div id="bubble"></div>
<div id="check_ans_div" style="display:none;">
<input type="text" id="txt_answer" />
<input type="submit" value="Check Answer" onclick="checkanswer()" />
</div>
<div id="feedback"></div>
JS changes:
var number1 = function() {
var numbx = Math.floor(Math.random() * 41) + 10;
return numbx;
}
var number2 = function() {
var numby = Math.floor(Math.random() * 41) + 10;
return numby;
}
var numb1=0; var numb2=0;
var userAnswer = function() {
numb1 = number1();
numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
if(document.getElementById('check_ans_div').style.display=='none')
document.getElementById('check_ans_div').style.display='block';
document.getElementById('txt_answer').value='';
}
function checkanswer(){
var userInput= document.getElementById('txt_answer').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
}