Reputation: 2260
I'm learning javascript and I decided to create simple Rock, Paper, Scissors game. I want to make it controllable by buttons. So I made this 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 in .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 Rock button it will change var user to rock but it doesn't. After I click rock and then Debug button I get "You chose none".
Upvotes: 8
Views: 68376
Reputation: 248
<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 chose " + user);
}
Upvotes: 8
Reputation: 6888
Maybe try this.. cleaner 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);
});
});
Upvotes: 1
Reputation: 17288
The selections should be encased in the quotes, javascript is looking for the variables named paper etc.
<button onClick="user(rock)">Rock</button>
<button onClick="user(paper)">Paper</button>
<button onClick="user(scissors)">Scissors</button>
Upvotes: 0
Reputation: 4558
The other answers are fixing some issues. There is also a problem with the way you're calling the functions as you're passing rock
as a variable, you need to use a string:
<button onClick="user('rock')">Rock</button>
Unless you're declaring the variables somewhere but it's not shown in your code.
Upvotes: 0
Reputation: 37085
Seems like a scoping issue. Try removing the var inside the function.
Upvotes: 0
Reputation: 4143
The var
keyword used in the scope of a function will declare a new local variable.
Hence, in the global scope, user
retains the value "none"
.
Upvotes: 1
Reputation: 20638
One problem:
var user = "none";
function user(choice){
var user = choice;
}
One variable of user is hiding the other variable of user.
And having a function and variable with the same name is a BAD idea.
Upvotes: 2
Reputation: 1474
var
is used for declaring a variable. You don't need to declare user
variable again in user
function. You just need to assign a value to declared one.
var user; //declaration
function user(choice) {
user = choice; //assignment
}
Upvotes: 4