JavaScript with if statements and buttons - javascript

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

Related

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

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>

How can i add numbers to a variable in JS?

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(){
...
}

javascript win counter for dice game

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div.dice {
float:left;
width:32px;
background:#F5F5F5;
border:#999 1px solid;
padding:10px;
font-size:24px;
text-align:center;
margin:5px;
}
</style>
<script>
function rollDice() {
var die1 = document.getElementById("die1");
var die2 = document.getElementById("die2");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var wins = documentgetElementById("doubles");
var diceTotal = d1 + d2;
die1.innerHTML = d1;
die2.innerHTML = d2;
status.innerHTML = "You rolled " + diceTotal + ".";
if (d1 == d2) {
status.innerHTML += " DOUBLES! You get a free turn!!";
}
}
</script>
</head>
<body>
<div id="die1" class="dice">0</div>
<div id="die2" class="dice">0</div>
<button onclick="rollDice()">Roll Dice</button>
<h2 id="status" style="clear:left;"></h2>
<br>Wins:
<h5 id="doubles" style="clear:left;"></h5>
<br>
</body>
</html>
I want to have it so the Wins is updated every time they roll doubles
I still noob at this i was thinking it would be a simple line of code added after the
status.innerHTML += " DOUBLES! You get a free turn!!";
doubles.innerHTML =+ Wins;
put var wins = document.getElementById("doubles"); ??? i know im doing something wrong any help would be awesome! Sincerely LM
http://jsfiddle.net/GkPEA/
var wins = documentgetElementById("doubles"); has a typo and should be var wins = document.getElementById("doubles");
As for updating the win counter, you need to convert the element's value to an int before adding 1. However, I'd suggest storing the win count in a global variable as opposed to text in a DOM element.
if (d1 == d2) {
status.innerHTML += " DOUBLES! You get a free turn!!";
var winsCount = parseInt(wins.innerHTML) || 0;
wins.innerHTML = winsCount + 1;
}
I see your problem. There is a typo on the line where you declare the variable wins, documentgetElementById() should be document.getElementById(). Start off with 0 in the wins h5 and then every time the player wins do this code:
var previouswins = document.getElementById("doubles").innerHTML;
var presentwins = parseInt(previouswins, 10) + 1;
document.getElementById("doubles").innerHTML = presentwins;
That code creates a variable called previouswins that is basically just everything that's inside the doubles h5. Then we parse that as an integer, which means that javascript can now do math functions with it and then we add one. All that's left to do after that is write the new variable to the doubles h5.
Note that when using parseInt, you should always specify a radix (the base of number), as this does not default to 10 like you might expect. You can read more about this on MDN.

Categories