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 »
  1. I have created three button elements with onclick() event attribute.
  2. 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() method
let buttonList = document.querySelectorAll("button");
  buttonList.forEach(function(i){
    i.addEventListener("click", function(e){
     alert(e.target.innerHTML);
    })
  })
Try it Yourself »
  1. 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>
  2. 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.
  3. 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.
  4. 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);
      })
    })