Displaying buttons and printing a variable in javascript - javascript

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

Related

JavaScript with if statements and buttons

I'm very new to JavaScript, but I have some knowledge of c, and a good amount of knowledge about HTML.
My issue in this project is that I want the second button (the one that onclick should run the firstx2 function) to become visible only after the points are 100 or more, and I'm not sure how to go about this. Also need the button to disappear after they click it. Thanks!
var points = 0;
var pointMulti = 1;
function addPoints() {
points = points + pointMulti;
document.getElementById("pointdisplay").innerHTML = "You have " + points
+ " points!";
}
function firstx2() {
pointMulti *= 2;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " +
pointMulti + "!"
}
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button onclick="firstx2">x2 Multiplier. Cost: 100</button>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
</body>
</html>
You did not call the function properly.
changed onclick="firstx2" to onclick="firstx2()"
Also Added few edits to the logic where the score reduces by 100 when you purchase x2 Multiplier.
But the main problem was calling the function.
var points = 0;
var pointMulti = 1;
function addPoints() {
points = points + pointMulti;
document.getElementById("pointdisplay").innerHTML = "You have " + points +
" points!";
}
function firstx2() {
if (points >= 10) {
pointMulti = pointMulti * 2;
points = points - 10;
document.getElementById("pointdisplay").innerHTML = "You have " + points +
" points!";
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " +
pointMulti + "!";
}
}
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button onclick="firstx2()">x2 Multiplier. Cost: 100</button>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
Ok, here's how you do it:
correct the onclick part of the second button, like others have mentioned
add an id to the second button and add styles to it: display:none; to hide it
make it appear in addPoints (set display:inline;)
regarding disappearing, you may set display:none; back again
the particular implementation below works like you described: the multiply button will appear after each click on the first button when you have >=100 points (I've set initial points to 98 for quicker testing):
var points = 98;
var pointMulti = 1;
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + points + " points!";
if(points >= 100) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
pointMulti *= 2;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
<!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>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
</body>
</html>
If you'd like the second button to be displayed only once, you should make an extra variable, something like multiplier_got_available, set and check it accordingly. Also, it seems that you wanted to add points -= 100 to firstx2.
First, change
<button onclick="firstx2">x2 Multiplier. Cost: 100</button>
to
<button onclick="firstx2()">x2 Multiplier. Cost: 100</button>
You need the parenthesis.
Second, this should work (replace your firstx2 function with this)
function firstx2(){
if(points >= 100){
pointMulti *= 2;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti + "!";
document.getElementById("pointdisplay").innerHTML = "You have " + points;
points -= 100;
}
}

JavaScript button not running function or disappearing after clicked

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

How do I use inner.HTML in a function?

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>

Vanilla JavaScript: How to make the second number of two random numbers always higher than the first

I am trying to make a children's math quiz and so far I have been able to do the following: Get two random numbers between 0 and 10 to appear; Make the + or - operator random; Give feedback if the answer is wrong or right; keep score;
There is one problem that I am facing though is that in some cases the operator will be - and the second random number will be greater than the first resulting in a - number answer. As can be seen inside the code below, I have tried using an if statement within an if statement and also a while statement within an if statement. Both do not produce the desired results.
I appreciate any advise on how to fix my problem.
Code:
document.getElementById("button1").addEventListener("click", question);
var plusMinus = document.getElementById("plusMinus");
var counter = 0;
function question(){
var startButton = document.getElementById("button1");
var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");
var decider = Math.random();
counter ++;
if(decider<0.5){
plusMinus.textContent = "+"
}
else{plusMinus.textContent = "-"
};
button1.textContent = "Round" + counter;
number1.textContent = Math.floor(Math.random()*11);
number2.textContent = Math.floor(Math.random()*11)
/*Solution No.1 that failed:
if(plusMinus.textContent == "-"){
if(number2.textContent < number1.textContent){
Math.floor(Math.random()*11);
}
}
else{Math.floor(Math.random()*11);
}*/
/*Solution No.2 that also failed:
if(plusMinus.textContent == "-"){
while(number2.textContent < number1.textContent){
Math.floor(Math.random()*11);
}
}
else{Math.floor(Math.random()*11);
}*/
};
document.getElementById("button2").addEventListener("click", answer);
var totalScore = 0;
function answer(){
var num1 = parseInt(document.getElementById("number1").textContent, 10);
var num2 = parseInt(document.getElementById("number2").textContent, 10);
var answer = parseInt(document.getElementById("userAnswer").value, 10);
var feedBack = document.getElementById("feedBack");
var scoreReport = document.getElementById("score");
if (plusMinus.textContent == "+"){
if(answer == num1 + num2) {
feedBack.textContent = "Well Done!";
totalScore = totalScore + 10;
}
else {
feedBack.textContent = "Try again!";
}
}
else {
if(answer == num1 - num2){
feedBack.textContent = "Well Done!";
totalScore = totalScore +10;
}
else {feedBack.textContent = "Try again!"};
}
scoreReport.textContent = totalScore;
};
Here is a jsfiddle: http://jsfiddle.net/way81/r9vdLkzp/1/
You can check if its minus. Check if the number2 is bigger than the number1 then swap them.
Something like this:
if(plusMinus.textContent == '-' && number2.textContent > number1.textContent) {
var a = number2.textContent;
number2.textContent = number1.textContent;
number1.textContent = a;
}
When you call answer() you are getting the values again. So the fact that you swapped the order won't have any effects in the rest of your logic and you won't get any negative numbers.
Snippet:
document.getElementById("button1").addEventListener("click", question);
var plusMinus = document.getElementById("plusMinus");
function question(){
var startButton = document.getElementById("button1");
var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");
var decider = Math.random();
button1.textContent = "Again";
number1.textContent = Math.floor(Math.random()*11);
number2.textContent = Math.floor(Math.random()*11);
if(decider<0.5){
plusMinus.textContent = "+"
}
else{plusMinus.textContent = "-"};
if(plusMinus.textContent == '-' && number2.textContent > number1.textContent) {
console.log('swapped')
var a = number2.textContent;
number2.textContent = number1.textContent;
number1.textContent = a;
}
};
document.getElementById("button2").addEventListener("click", answer);
function answer(){
var num1 = parseInt(document.getElementById("number1").textContent, 10);
var num2 = parseInt(document.getElementById("number2").textContent, 10);
var answer = parseInt(document.getElementById("userAnswer").value, 10);
var feedBack = document.getElementById("feedBack");
var scoreReport = document.getElementById("score");
var totalScore = 0;
if (plusMinus.textContent == "+"){
if(answer == num1 + num2) {
feedBack.textContent = "Well Done!";
} else {
feedBack.textContent = "Try again!";
}
}
else {
if(answer == num1 - num2){
feedBack.textContent = "Well Done!";
} else {feedBack.textContent = "Try again!"};
}
for(count=0; count <=10; count++){
if(plusMinus == "+" && answer == num1+num2){
totalScore +1;
}
else if(plusMinus == "-" && answer == num1-num2){
totalScore -1;
}
}
scoreReport.textContent = totalScore;
};
*{
border: 2pt solid black;
}
p {
height: 20px;
width: 50px;
font-family: impact;
size: 16pt;
text-align: center;
}
<body>
<div>
<button id = "button1">Start!</button>
<p id = "number1"></p>
<p id = "plusMinus">+</p>
<p id = "number2"></p>
<input id = "userAnswer" type=text>
<button id = "button2">Answer</button>
<p id = "feedBack"></p>
<p id = "score">Score: 0</p>
</div>
<script src="randomMathsTest.js"></script>
</body>
You could use the first random number as an argument in creating the second random number. For instance:
var num1 = Math.floor(Math.random()*11);
var num2 = num1+ Math.floor(Math.random()*(10-num1));
...or something similar. Just generate a random number between your first random number and 10 by creating a smaller range and adding the first number to the result.
Addendum
By following this method, you do skew the likelihood of larger numbers appearing in your problems. #Joel's answer would not suffer from this.
Here's a generalized solution you could use (it's not entirely adapted to your current code example, but I'm sure you'll be able to get it to work):
// create a random Boolean that determines whether it's minus
var isMinus = !Math.round(Math.random());
// create an array of two random numbers from 0-10
var numbers = [Math.floor(Math.random()*11), Math.floor(Math.random()*11)];
// if isMinus, sort numbers ascending, else keep as-is
numbers = isMinus ? numbers.sort().reverse() : numbers;
// assign the proper sign to the DOM element
plusMinus.textContent = isMinus ? '-' : '+';
// assign the proper array elements to the DOM elements
number1.textContent = numbers[0];
number2.textContent = numbers[1];

Taking var with JS prompt - how can I make it through HTML form?

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.");
}
}

Categories