tags:

views:

160

answers:

4

I have 2 anchor tags

<li><a id="tab1" href="#tabs-1">Issue</a></li>
<li><a id="tab2" href="#tabs-2">Change Request</a></li>

I have the following jquery:

$('a').click(function(event) {
                                alert($('a').attr("id"));
            });

What happens: I always get "tab1" in the pop up

What I need: when user clicks on an anchor tag, its id needs to be displayed in the pop up

+7  A: 

Your problem lies in the alert statement: with $('a'), you aren't referencing the clicked <a> element in the alert statement—you're retrieving the first <a> element in the document.

Instead, to reference the clicked element, replace $('a') with $(this):

$('a').click(function(event) {
    alert($(this).attr("id"));
});
Steve Harrison
thanks for the quick replyI get an error likeMessage: Object doesn't support this property or methodLine: 57Char: 17Code: 0If i replace this.attr("id") with this the error goes off but the popup shows the full url http://sever/folder/#tab1
balalakshmi
@balalakshmi: OK, it seems jQuery likes `$(this)` rather than the plain JavaScript `this`. Does it work if you use `$(this)` instead (see my updated code snippet)?
Steve Harrison
+1 for the spending the time to explain why the original code does not work.
Rosdi
+4  A: 

Try

$('a').click(function(event) {
    var currentElemID = $(this).attr("id") // or you can use this.id
});
rahul
A: 

You can get any element attribute using attr() so:

$('a').attr('id');
Sam3k
A: 

If you only need to access the id, then using jQuery is an unnecessary overhead:

$('a').click(function(event) {
    alert(this.id);
});
RoToRa