Home > Back-end >  How do I get my button name to act as my answer for a text input?
How do I get my button name to act as my answer for a text input?

Time:08-08

I'm currently doing a rock paper scissors game where it should take the button name(rock, paper, or scissors) and use that as the player input.

So far my project takes the player's choice by prompting a text box where I can type the answer and works as expected. Is there a way in javascript where I can take the text from the buttons and convert that into the answer?

CodePudding user response:

Or

document.querySelectorAll("button").forEach(function(button) {
  button.addEventListener('click', function(ev) {
    var value = button.getAttribute("data-type");
    console.log("you pressed "   value);
  })
})
<button data-type="rock">Rock</button>
<button data-type="paper">Paper</button>
<button data-type="scissors">Scissors</button>

CodePudding user response:


<button onclick="submit('rock')">Rock</button>
<button onclick="submit('paper')">paper</button>
<button onclick="submit('scissors')">scissors</button>
function submit(answer){
    // there's your answer: answer (it is a local variable)
}

CodePudding user response:

you can easily use this code to get name of button witch you click. i use p tag to show the name of button witch clicked. you can remove it and use the javascript code to youer next use

function getInfo(event){
document.getElementById('p').innerHTML = event.target.innerHTML
}
<button type="button" onclick="getInfo(event)">Rock</button>
<button type="button" onclick="getInfo(event)">paper</button>
<button type="button" onclick="getInfo(event)">scissors</button>
<p id="p"></p>

  • Related