kushal jain
kushal jain

Reputation: 85

how to show id of a button using Jquery?

Here it is demo of my code. I just want to show Id of button while it is saying undefined

Demo.

Code:

$('#btn').on('click', function () {
    var $this = $(this);
    var ID = $(this).id;
    alert(ID);

});

Upvotes: 0

Views: 115

Answers (10)

Jay
Jay

Reputation: 402

try this and you will get button id-

$('#btn').on('click', function () {        
    alert(this.id);        
});

second method-

$('#btn').click(function () {
  alert(this.id); 
)};

After Update - Please Try

Upvotes: 0

Mohammad Areeb Siddiqui
Mohammad Areeb Siddiqui

Reputation: 10179

Approach 1

Use $.prop().

$('#btn').on('click', function () {
    alert($(this).prop("id"));
});

Demo.


Approach 2(recommended)

Use this.id.

$('#btn').on('click', function () {
    alert(this.id);
});

Demo.

Upvotes: 0

Stefan Surkamp
Stefan Surkamp

Reputation: 992

You can use .attr(attribute).

$('#btn').on('click', function () {
    var ID = $(this).attr('id');
    alert(ID);

});

http://jsfiddle.net/vN88X/11/

Upvotes: 0

achudars
achudars

Reputation: 1506

What about this:

$(".a").click(function(){
    var id = this.id;
    alert(id);
});

Upvotes: 1

user2586839
user2586839

Reputation:

Demo http://jsfiddle.net/vN88X/8/

$('#btn').click(function () {
    alert($(this).attr('id'));
});

Upvotes: 1

dsgriffin
dsgriffin

Reputation: 68566

You've got it a little mixed up - you need to be using this.id. There is no id "method" in jQuery, however getting it via. .attr('id') is possible (although there's no real need for that).

Upvotes: 2

Nagesh Salunke
Nagesh Salunke

Reputation: 1288

It Should be

$('#btn').on('click', function () {
var ID = $(this).attr('id');
alert(ID);

 });

Here is Updated Demo http://jsfiddle.net/vN88X/3/

Upvotes: 0

David Level
David Level

Reputation: 353

Try

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

You will get the "id" attribute of the element.

Upvotes: 0

Lucas Willems
Lucas Willems

Reputation: 7063

The right code is the following :

$('#btn').click(function () {
    var ID = $(this).attr('id');
    alert(ID);
});

Have a look to the fiddle : http://jsfiddle.net/vN88X/6/

Upvotes: 0

gdoron
gdoron

Reputation: 150253

Simply use the DOM native functions and properties:

$('#btn').on('click', function () {
    alert(this.id);    
});

If you decided you want to use jQuery for the overkill:

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

Upvotes: 2

Related Questions