JavaScript - onClick to get the ID of the clicked button
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>
USING PURE JAVASCRIPT: I know it's late but may be for the future people it can help:
In the HTML part:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
In the Javascipt Controller:
function reply_click()
{
alert(event.srcElement.id);
}
This way we don't have to bind the 'id' of the Element at the time of calling the javascript function.