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() { }
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.
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 .
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With