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;
}
Dalton Cézane
  • 3,672
  • 2
  • 35
  • 60
nightspite
  • 101
  • 1
  • 8
  • Related: https://stackoverflow.com/questions/18410341/using-multiple-buttons-on-same-function-that-redirects-to-different-functions/18410383 and https://codereview.stackexchange.com/questions/18160/different-way-of-writing-multiple-click-functions – jarmod Oct 18 '18 at 22:10

2 Answers2

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;
}
Petar
  • 539
  • 5
  • 14
  • 1
    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 Oct 18 '18 at 22:15
  • 1
    @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 – Petar Oct 18 '18 at 22:22
  • Be careful with [*NodeList.forEach*](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach), it hasn't been added to the [*DOM Living Standard*](https://dom.spec.whatwg.org/#interface-nodelist) yet and is not supported everywhere. – RobG Oct 18 '18 at 22:51
1
inputs = document.getElementsByClassName('pick');

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