0

I am using jQuery to set a click event for a number of elements that share the same class but different IDs. However, I need to be able to get these IDs. Is there a way to do this?

$(".buynowlink").click(function(item) {

});

From what I researched; 'item' is the element being triggered. Im not sure how to get the Id of the object.

Albzi
  • 15,431
  • 6
  • 46
  • 63
Andrei0427
  • 573
  • 3
  • 6
  • 18
  • possible duplicate of [Getting the ID of the element that fired an event using jQuery](http://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event-using-jquery) – MackieeE Apr 10 '14 at 10:45
  • from speakers of my laptop, i hear people are typing answer in a hurry – doniyor Apr 10 '14 at 10:45

6 Answers6

3

Try this:

alert(this.id);

See what I did there? "Try this"? Hehehe ... I need coffee.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • It's frustrating when someone posts after you, but gets more upvotes, but yours has humor so I feel like if anything, I've let everyone down. – Albzi Apr 10 '14 at 10:46
  • @BeatAlex In my defence, I seem to recall your answer was originally `$(this).id`, which is incorrect :p But I could be wrong, so many answers... – Niet the Dark Absol Apr 10 '14 at 10:48
  • It was `$(this).id` I'll admit :P, but I was caught up in the moment of jQuery and got `$` happy. Oops haha – Albzi Apr 10 '14 at 10:49
1

Use $(this) to get current element

$(".buynowlink").click(function(item) {
  $(this).attr('id') // This will return clicked element id
});
Sridhar R
  • 20,190
  • 6
  • 38
  • 35
1

JsFiddle

Try this:

$(".buynowlink").click(function(item) {
   alert(this.id);
});

this.id is all you need. You can then assign this to a variable to use later.

Albzi
  • 15,431
  • 6
  • 46
  • 63
1

Try this

$(".buynowlink").click(function(item) {
   $(item).attr("id");
});
Anubhav Ranjan
  • 1,558
  • 3
  • 18
  • 32
0

use .attr() function of Jquery.

$(".buynowlink").click(function(item) {
   var id_of_clicked_element = $(this).attr('id');
});
doniyor
  • 36,596
  • 57
  • 175
  • 260
0

This might help you to get it better:)

http://jsfiddle.net/seAy6/

$('.buynowlink').click(function(){
    idName = this.id;
    $('.result').html('Clicked ID : '+idName);
});
Jagadeesh J
  • 1,211
  • 3
  • 11
  • 16