Arshad Ali Arshad Ali - 3 months ago 11
HTML Question

get Id of link and open alert javascript

I have found this example to open an alert in javascript as



function reply_click(clicked_id)
{
alert("You have clicked Button " + clicked_id);
}

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





I'm confused about how to get this desired behavior when clicking on a link, I've tried in following way



function reply_click(clicked_id)
{
alert("You have clicked Link " + clicked_id);
}

<a id="1" href="javascript:reply_click(this.id);">Link 1</a>
<a id="2" href="javascript:reply_click(this.id);">Link 2</a>
<a id="3" href="javascript:reply_click(this.id);">Link 3</a>





when I try this code I get result as

You have clicked Link undefined


could not find way to get rid of
undefined
and get actual
id
of the link!

Answer

Try following

function reply_click(clicked_id)
{
    alert("You have clicked Link " + clicked_id);
}
<a id="1" href="#" onClick="reply_click(this.id)">Link 1</a>
<a id="2" href="#" onClick="reply_click(this.id)">Link 2</a>
<a id="3" href="#" onClick="reply_click(this.id)">Link 3</a>