0

I'm trying to create a rock paper scissors game using javascript and I can't seem to figure out a way to store a button's value inside a variable after the button is clicked.

Also, using data-set value for the buttons, if say the code will work, does it store a string value inside the variable?

HTML code

javascript code

note: In the javascript code's start function; I'm just trying to see if my computer choice and player choice code is working.

I'm trying to use the document.querySelectorAll along with the dataset value to make the code as clean as possible. Please let me know if my approach with this is wrong.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    Welcome to Stack Overflow! Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) - post CODE not pictures of code – mplungjan Jan 28 '23 at 13:32
  • Here is what you meant to do - delegate from the container instead of having inline event handler: `const h1 = document.querySelector('h1'); document.querySelector('.choice').addEventListener('click', (e) => { const tgt = e.target; const result = getComputerChoice(), pchoice = tgt.textContent; h1.innerHTML = \`Computer choice: ${result}; Player choice: ${pchoice}\`; })` assuming you have a getComputerChoice function somewhere. This code replaces all the code you posted – mplungjan Jan 28 '23 at 13:37
  • @mplungjan What happens if the user clicks between the buttons? – FiddlingAway Jan 28 '23 at 13:45
  • 1
    @FiddlingAway then you extend it a tiny bit `const h1 = document.querySelector('h1'); document.querySelector('.choice').addEventListener('click', (e) => { const tgt = e.target; if (!tgt.matches('.button-game')) return; const result = getComputerChoice(), pchoice = tgt.textContent; h1.innerHTML = \`Computer choice: ${result}; Player choice: ${pchoice}\`; })` – mplungjan Jan 28 '23 at 13:47

0 Answers0