Changing variable by html button

Kyrbi picture Kyrbi · Mar 16, 2013 · Viewed 56.7k times · Source

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".

Answer

llvk picture llvk · Mar 16, 2013
<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);
}