JavaScript - onClick to get the ID of the clicked button

Bin Chen picture Bin Chen · Jan 28, 2011 · Viewed 1.3M times · Source

How do find the id of the button which is being clicked?

<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>

function reply_click()
{
}

Answer

shamittomar picture shamittomar · Jan 28, 2011

You need to send the ID as the function parameters. Do it like this:

<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
    
<script type="text/javascript">
  function reply_click(clicked_id)
  {
      alert(clicked_id);
  }
</script>

This will send the ID this.id as clicked_id which you can use in your function. See it in action here.