SkyeBoniwell
SkyeBoniwell

Reputation: 7092

getting ID of button pressed with jquery

I have jQuery code that I use for multiple buttons. I'm trying to get the ID of the button that is pressed, but all I get is 'undefined'. I have tried both methods below, but both give the same results.

What am I doing wrong?

Thanks!

$(document).ready(function () {


    $("#btnSearch, #btnDirectorSearch, #btnEditorSearch, #btnViewableSearch").click(function () {

         alert($(this).id);
         alert(this.id);
     });

 });

Upvotes: 1

Views: 122

Answers (5)

Martin Geisler
Martin Geisler

Reputation: 73748

When the click handler is executing, jQuery has made sure to set this to the DOM element that triggered the event. That means that you can use

alert(this.id)

to access the id attribute. This is because the id attribute is exposed like this — no jQuery involved.

You can also choose to use jQuery's attr method instead:

alert($(this).attr("id"))

This way you construct a jQuery object from this, and then proceed to use the attr method on that object. Note, that $(this) won't have an id attribute.

Upvotes: 1

amit ghosh
amit ghosh

Reputation: 276

you can get the id from

$(document).ready(function () {
$("#btnSearch, #btnDirectorSearch, #btnEditorSearch, #btnViewableSearch").click(function () {
alert ($(this).attr("id"));
});
});

Upvotes: 1

Mathew Thompson
Mathew Thompson

Reputation: 56429

Try using attr:

$(this).attr("id")

Upvotes: 5

jahroy
jahroy

Reputation: 22692

Check out the jQuery.attr() method.

It can be used to extract the value of any attribute.

In your case, you're after the id attribute:

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

It can also be used to set an attribute:

$(this).attr('id', 'funkyId');

Whenever you have a question, your best bet is to go straight to the jQuery documentation (which is excellent).

I was led straight to the above link when I googled "jquery get id".

Upvotes: 2

Adil Shaikh
Adil Shaikh

Reputation: 44740

You need to do this -

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

Upvotes: 2

Related Questions