Home >Web Front-end >JS Tutorial >How Can I Get the ID of a Clicked Button Using JavaScript?
Get the ID of the Clicked Button Using JavaScript
When using HTML buttons with an onClick event, it can be useful to retrieve the ID of the clicked button. This information can be utilized for various purposes, such as selecting the appropriate action or displaying specific data.
To achieve this, you can modify your HTML and JavaScript code as follows:
<button>
In this updated HTML, each button now calls the reply_click function and passes its own ID as a parameter when clicked.
The JavaScript function is also modified:
function reply_click(clicked_id) { alert(clicked_id); }
Now, when a button is clicked, the reply_click function is triggered and the ID of the clicked button is passed as the clicked_id parameter. This allows you to easily identify the specific button that was clicked and perform the necessary actions.
To demonstrate how this works, you can replace your original code with the modified versions and click on any of the buttons. You should see an alert box displaying the ID of the clicked button.
The above is the detailed content of How Can I Get the ID of a Clicked Button Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!