I have three button in html:
<button value="Rock" onclick="displayResult()">Rock</button>
<button value="Paper" onclick="displayResult()">Paper</button>
<button value="Scissors" onclick="displayResult()">Scissors</button>
In displayResult() function (wrriten once for 3), how can I get value from the button that I click? If I set ids for all 3 button, I have to write 3 display function to get value from a seperate button:
let displayResultForRock = () => {
let value = document.getElementById('rock').value;
}
CodePudding user response:
Just attach event listeners to the buttons, and then log the textContent
of each.
const buttons = document.querySelectorAll('button');
buttons.forEach(button => {
button.addEventListener('click', handleClick, false);
});
function handleClick() {
console.log(this.textContent);
}
<button>Rock</button>
<button>Paper</button>
<button>Scissors</button>
Or use event delegation:
const buttons = document.querySelector('#buttons');
buttons.addEventListener('click', handleClick, false);
function handleClick(e) {
if (e.target.matches('button')) {
console.log(e.target.textContent);
}
}
<div id="buttons">
<button>Rock</button>
<button>Paper</button>
<button>Scissors</button>
</div>
CodePudding user response:
Please use this code. you can update your displayResult
function like this.
function displayResult(event) {
console.log(event.target.value)
}
<button value="Rock" onclick="displayResult(event)">Rock</button>
<button value="Paper" onclick="displayResult(event)">Paper</button>
<button value="Scissors" onclick="displayResult(event)">Scissors</button>
CodePudding user response:
const btns = document.querySelectorAll("button")
btns.forEach(b => b.onclick = e => result.innerText = e.target.value)
<button value="Rock">Rock</button>
<button value="Paper">Paper</button>
<button value="Scissors">Scissors</button>
<div id="result"></div>
CodePudding user response:
why not just pass the value as parameter to the function like this:
<button value="Rock" onclick="displayResult("Rock")">Rock</button>