How to get value of clicked button in JavaScript
If you are thinking about how to get the value of a button clicked by one person in JavaScript, then in this article you will learn how to get the value of a clicked button.
If you have a couple of button, then you can add the onclick event for each button.
Demo - Get the value of clicked button <button onclick="alert(this.innerText)" >
button 1
</button>
<button onclick="alert(this.innerText)">
button 2
</button>
<button onclick="myFun(this)">
button 3
</button>
Try it Yourself »
- I have created three button elements with onclick() event attribute.
- Inside the onclick() event, I have called alert() method to alert the button value.
If you have a lot of buttons, then the above approach is not elegant. So, in this case we need to create a forEach() method.
Get button value dynamically using forEach() methodlet buttonList = document.querySelectorAll("button");
buttonList.forEach(function(i){
i.addEventListener("click", function(e){
alert(e.target.innerHTML);
})
})
Try it Yourself »
- Suppose we have five buttons (you can have many buttons).
<button>Button 1</button> <button>Button 2</button> <button>Button 3</button> <button>Button 4</button> <button>Button 5</button>
- Select all the buttons and store in a variable using the querySelectorAll() method.
let buttonList = document.querySelectorAll("button");
buttonList variable returns a nodeList that represents all the buttons. - The forEach() method calls a function for each element of an array.
buttonList.forEach(function(i){ })
We passed an anonymous function to the forEach() method and included a parameter i that will represent each button. - Finally, when a button is clicked, the value of the clicked button will be alerted.
buttonList.forEach(function(i){ i.addEventListener("click", function(e){ alert(e.target.innerHTML); }) })
Conclusion
In this article, you have learned how to get value of clicked button using javascript.
Also read:
How to create button dynamically in Javascript. save
listen
AI Answer
How to get value of clicked button in JavaScript
1
If you are thinking about how to get the value of a button clicked by one person in JavaS…
asked
Apu
1 answers
2915
If you are thinking about how to get the value of a button clicked by one person in JavaS…
Answer Link
answered
Apu
<button id="myButton" value="My Value">
Click Me
</button>
<script>
document.getElementById('myButton').addEventListener('click', () =>{
const myValue = document.getElementById( 'myButton').value;
console.log (myValue); // Output "My Value"
});
</script>