How can i add numbers to a variable in JS? - javascript

I have been trying to do a simple game where you try to get the right number as the random number. If you win, you get 1 point. But I wasn't able to give that point. Here is what i have done :
<html>
<head>
<title>Luck Game</title>
<script>
function onClick(){
var number = Math.floor(Math.random()*10);
var usernumber = document.getElementById("input").value ;
var points = 0;
document.getElementById("Answer").innerHTML = number ;
document.getElementById("points").innerHTML = "Points in your account : " + points;
if(usernumber == number){
document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points = points + 1;
}
else{
document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
}
}
</script>
</head>
<body>
<input id="input"></input>
<p id="Answer"></p>
<button onClick="onClick()"></button>
<p id="WIN?"></p>
<p id="points"></p>
</body>
But the "points = points + 1" is not working !
what is wrong ? please help me .

You should declare your var points outside click function. E.g :
<script>
var points = 0;
function onClick(){
var number = Math.floor(Math.random()*10);
var usernumber = document.getElementById("input").value ;
document.getElementById("Answer").innerHTML = number ;
document.getElementById("points").innerHTML = "Points in your account : " + points;
if(usernumber == number){
document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points = points + 1;
}
else{
document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
}
}
</script>
So the counter will be saved somewhere else without being resetted everytime function procs.

The way you've written it, points is a variable local to the onClick() function so it will get reset to zero each time the function is called. If you pull the initialization of points out of onClick() then you will be able to safely increment its value:
<script>
var points = 0;
function onClick(){
var number = Math.floor(Math.random()*10);
var usernumber = document.getElementById("input").value ;
document.getElementById("Answer").innerHTML = number ;
document.getElementById("points").innerHTML = "Points in your account : " + points;
if(usernumber == number){
document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points++;
} else {
document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
}
}
</script>

Declare var points outside function:
var points = 0;
function onClick(){
...
}

Related

How to fix [objectHTMLButtonElement] problem in JavaScript

Sorry to bother all of you. I know, this question has been asked multiple times. However, I just couldn't fix my problem.
So, I've been trying to create a tennis scoring system that shows the score when you click one of two buttons, the win button or the lose button. I have a button where they can add their name to the scoring system. When one player wins two sets the match is over. I then try to print their name saying, ____ won the match. When I try using the variable that printed their name before I get something that says: [objectHTMLButtonElement]. I've been trying for a long time to fix this and I don't know how to.
Here is the code:
document.getElementById("youName").onclick = function() {
var youName = prompt("Enter your name");
document.getElementById("youOutput").innerHTML = youName + ":";
}
let points = 0;
function win() {
points += 1;
document.getElementById("points").innerHTML = points;
if (points == 2) {
document.getElementById("finish").innerHTML = youName + " won the match";
}
}
<button id="youName">Your name</button>
<p id="youOutput"></p>
<button onclick="win()">Won the point</button>
<p id="points"></p>
<p id="finish"></p>
Thanks in advance.
Try to declare yourName in a global context
let yourName = null;
document.getElementById("youName").onclick = function () {
yourName = prompt("Enter your name");
document.getElementById("youOutput").textContent = `${yourName}`;
};
let points = 0;
function win() {
points += 1;
document.getElementById("points").innerHTML = points;
if (points == 2) {
document.getElementById(
"finish"
).textContent = `${yourName} won the match`;
}
}

How to make a number appear in a range from 0 to 9?

I am currently completing a project and have come across an error in my coding.
I have a button which calls a JS prompt box asking to enter an integer between 0 and 9.
This number is then used as a game where 3 random integers from 0 and 9 appear every second and when you click on the matching number your score increases.
This is my code so far:
<script>
function chooseNum()
{
var txt;
var person = prompt("Choose an integer between 0 and 9:");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = person;
}
document.getElementById("chosen").innerHTML = txt;
}
</script>
I want to know exactly how to display random integers in a range from 0 and 9.
Is a code like this on the right track?
<script>
var id = window.setInterval(function(){randomNumber();},1000);
function randomNumber()
{
var rand = Math.floor(Math.random()*9);
$('#number1').html(rand);
}
</script>
Can anyone point me in the right direction?
Cheers.
var txt;
function chooseNum()
{
var person = prompt("Choose an integer between 0 and 9:");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = person;
}
document.getElementById("chosen").innerHTML = txt;
}
chooseNum() ;
var id = window.setInterval(function(){randomNumber();},1000);
function randomNumber()
{
var rand = Math.floor(Math.random()* 9 + 1);
$('#number1').html(rand);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="chosen"></p>
<p id="number1"></p>

Displaying buttons and printing a variable in 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");

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

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];

Categories