Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick to get the ID of the clicked button

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() { } 
like image 462
Bin Chen Avatar asked Jan 28 '11 05:01

Bin Chen


People also ask

How do I get the clicked button ID?

To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

How do you get the ID of a clicked element in react?

To get the id of the element on click in React: Set the onClick prop on the element to a function. Access the id of the element on the currentTarget property of the event . For example, event.currentTarget.id returns the element's id .

How do I find the ID of a website button?

Chrome: Right-click anywhere on your screen, and click on the Inspect button or press CTRL + SHIFT + I or F12 from your keyboard. Firefox: Right-click anywhere on your screen, and click on the Inspect Element button.

Does Button have onclick?

The onclick attribute is an event attribute that is supported by all browsers. It appears when the user clicks on a button element. If you want to make a button onclick, you need to add the onclick event attribute to the <button> element.


2 Answers

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.

like image 178
shamittomar Avatar answered Sep 27 '22 23:09

shamittomar


In general, things are easier to keep organized if you separate your code and your markup. Define all of your elements, and then in your JavaScript section, define the various actions that should be performed on those elements.

When an event handler is called, it's called within the context of the element that was clicked on. So, the identifier this will refer to the DOM element that you clicked on. You can then access attributes of the element through that identifier.

For example:

<button id="1">Button 1</button> <button id="2">Button 2</button> <button id="3">Button 3</button>  <script type="text/javascript"> var reply_click = function() {     alert("Button clicked, id "+this.id+", text"+this.innerHTML); } document.getElementById('1').onclick = reply_click; document.getElementById('2').onclick = reply_click; document.getElementById('3').onclick = reply_click; </script> 
like image 22
Jason LeBrun Avatar answered Sep 27 '22 23:09

Jason LeBrun