0

I wonder how can I automate and ease javascript code. For example, I have got 3 buttons:

<button id="rock" class="pick" value="rock">rock</button>
<button id="paper" class="pick" value="paper">paper</button>
<button id="scissors" class="pick" value="scissors">scissors</button>

And I select these elements 3 times. So my question is how can I make it in just one instruction or function?

var userInput = '';

document.getElementById('rock').onclick = function() {
        userInput = 'rock';
}

document.getElementById('paper').onclick = function() {
        userInput = 'paper';
}

document.getElementById('scissors').onclick = function() {
        userInput = 'scissors';
}

I just wonder if I can make something like this:

document.getElementById(element).onclick = function() {
        userInput = element.value;
}
1

2 Answers 2

2

Yes you can. As a matter of fact you could have multiple elements, with an added event listener to them, that will give you their added value. Let's say you have 3 items, all with class gameCommands. Then you'd do something like this:

const commands = document.querySelectorAll(".gameCommands")
const userInput;
commands.forEach(command => command.addEventListener("click", getValue)

function getValue(){
  // THIS represents the element from which we call the function in this case.
  userInput = this.value;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Nice, elegant, generalised solution. +1 [ Although I'm not sure why you invented your own class name when the OP provided you with theirs, namely ".pick". ]
@CJK Oops, didn't even saw that he already had put classes in there, my bad :D Anyways, I hope he gets the point from the answer and that he found it helpful :D
Be careful with NodeList.forEach, it hasn't been added to the DOM Living Standard yet and is not supported everywhere.
1
inputs = document.getElementsByClassName('pick');

for (let i = 0; i < inputs.length; i++) {
  inputs[i].onclick = function() { userInput = this.value; } 
}

1 Comment

Yes, that was something I was thinking of. Thank you so much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.