Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing variable by html button

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

like image 564
Kyrbi Avatar asked Mar 16 '13 22:03

Kyrbi


People also ask

How do I change the value of a button in HTML?

If you want to change the text value for a HTML <button> element, then you need to update the button element innerText property instead of value property. JavaScript: const btn = document. getElementById("btn"); btn.

Can you assign variables in HTML?

Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.


1 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 chose " + user);
}                         
like image 113
llvk Avatar answered Sep 17 '22 22:09

llvk