Andris
Andris

Reputation: 1442

jQuery detect which id is clicked

I need to start function on document ready and also on button click. If button clicked, then need to detect which id clicked.

To start function I did

process_add_to_chart();// this is for document ready
$( '[id^="button_add_to_cart_"]' ).click(function(){
process_add_to_chart();
});

Then

function process_add_to_chart(){   }

Function starts, but how to get attr of id?

var id = $(this).attr('id');

does not work. Get undefined

Ah, sorry, seems must define global id inside

$( '[id^="button_add_to_cart_"]' ).click(function(){   });

Upvotes: 0

Views: 79

Answers (2)

RGS
RGS

Reputation: 5211

$('[id^="button_add_to_cart_"]').click(function(){
   process_add_to_chart(this);
});

function process_add_to_chart(obj){
  if(obj != null){
   var id = $(obj).attr('id');
  }
}

Pass clicked element object reference to your function.

Demo:

http://jsfiddle.net/9y8bLg22/

Upvotes: 1

Itay
Itay

Reputation: 16777

Because you call process_add_to_char inside the real handler (function () { ... })), you lose the original this "context" (the clicked element), and this is now the window object.

So, you need to bind the handler like this:

$( '[id^="button_add_to_cart_"]' ).click(process_add_to_chart);

And then, this will be the clicked element.


Another way is to use the call method to pass the this argument to the inner function, like this:

$( '[id^="button_add_to_cart_"]' ).click(function(){
     process_add_to_chart.call(this);
});

For further reading: JavaScript - The this keyword

Upvotes: 1

Related Questions