Jesper Jacobsen
Jesper Jacobsen

Reputation: 161

Why is this returning undefined? jquery

I have this line <table id='<?= $value['Name']?>'> in my PHP which just sets an ID which I can target.

This table is inside a <div> with id="god".

But when i click the table which has this script:

$("#god table").click(function(){
    var link = $(this).id;
    alert(link);
});

It alerts undefined - could you tell me why that is?

My best guess would be that it targets the <td> which I click on for the $(this) but I am not sure - and I do not know how to test that.

Upvotes: 0

Views: 3112

Answers (2)

Yotam Omer
Yotam Omer

Reputation: 15356

Use the following:

var link = this.id;

The jQuery object $(this) does not have a propery id.

Note: DO NOT use $(this).attr('id') when you can use this.id which is way more efficient. also, note that id is case sensitive so be consistent with "God" and "god".

Upvotes: 5

Sushanth --
Sushanth --

Reputation: 55740

   var link =  $(this).id;

Supposed to be

either

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

or

   var link =  this.id;

$(this) is a jQuery object. And it does not have the .id property

Upvotes: 1

Related Questions