Changing a variable using the html button

I am learning javascript and I decided to create a simple Rock, Paper, Scissors game. I want to make it button-driven. So I did it in html:

<div id="game"> <button onClick="user(rock)">Rock</button> <button onClick="user(paper)">Paper</button> <button onClick="user(scissors)">Scissors</button> <div id="result"></div> <br> <br> <button onClick="test()">DEBUG</button> </div> 

and this is in the .js file.

 var user = "none"; function user(choice){ var user = choice; } function test(click){ alert("You chose " + user); } 

So, I thought that after I click the Rock button, it will change the user var to rock, but that’s not the case. After I click rock and then the Debug button, I get "You have not selected anything."

+4
source share
8 answers
 <div id="game"> <button onClick="choose('rock')">Rock</button> <button onClick="choose('paper')">Paper</button> <button onClick="choose('scissors')">Scissors</button> <div id="result"></div> <br> <br> <button onClick="test()">DEBUG</button> </div> 

and

 var user; function choose(choice){ user = choice; } function test(click){ alert("You chossed " + user); } 
+4
source

One problem:

 var user = "none"; function user(choice){ var user = choice; } 

One user variable hides another user variable.

And having a function and a variable with the same name is the idea of ​​BAD.

+2
source

var used to declare a variable. You do not need to declare the user variable again in the user function. You just need to assign a value to the declared one.

 var user; //declaration function user(choice) { user = choice; //assignment } 
+1
source

The var keyword used in the scope of a function will declare a new local variable.

Therefore, the value "none" stored in the global user area.

+1
source

Sounds like a problem. Try removing var inside the function.

0
source

Other answers include fixing some issues. There is also a problem with the way you call functions, since you are passing rock as a variable, you need to use the line:

 <button onClick="user('rock')">Rock</button> 

If you do not declare variables somewhere, but this is not shown in your code.

0
source

Choices must be enclosed in quotation marks, javascript searches for variables named paper, etc.

 <button onClick="user(rock)">Rock</button> <button onClick="user(paper)">Paper</button> <button onClick="user(scissors)">Scissors</button> 
0
source

Maybe try this .. clean markup .. uses jQuery

 <div id="game"> <button class="user" data-name="rock">Rock</button> <button class="user" data-name="paper">Paper</button> <button class="user" data-name="scissors">Scissors</button> <div id="result"></div> <br> <br> <button id="test">DEBUG</button> </div> $(document).ready(function() { var user = "none"; $(".user").click(function() { user = $(this).attr("data-name"); }); $("#test").click(function() { alert(user); }); }); 

http://jsfiddle.net/rQDbe/

0
source

All Articles