GeekedOut
GeekedOut

Reputation: 17185

jQuery doesn't recognize an attribute from a <a> tag

I have this sort of a link:

<a class="image_button" data-problem_id="157"  style="display: inline;" href="#"><span>See Solutions Members Have Already Suggested</span></a>

and then I try to get the id like this:

var problem_id = $(this).attr("data-problem_id");

but it ends up being undefined. Any idea why? In other cases I did what seems to be exactly this, and I was able to get the problem_id

Thanks!

Upvotes: 0

Views: 81

Answers (3)

skub
skub

Reputation: 2306

I think the problem is that $(this) is not the hyperlink object that you think it is. You could go to Console.log and see what the object really is. Also have you tried using:

var problem_id = $('.image_button').attr('data-problem_id'); 

Upvotes: 0

Alxandr
Alxandr

Reputation: 12421

I think I found your error, though it's outside the scope of your problem. The point is, the this is a div, and not your button. How you change this you need to see for yourself. You can either reassign the click (instead of $("#div_id").live('click', blabla); do $("#button_id").live('click', blabla);, or you can run the check on the click target.

This would look something like:

$('#div_id').live('click', function(evt) {
    var btn = $(evt.target).closest('a');
    var data_thingy = btn.data('data_thingy');
});

[Edit]
You can btw also do this: $('#div_id a').live('click', blabla). The this-object will then be the actual button.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

I believe you can use:

$(this).data("problem_id");

to access data attributes.

Upvotes: 2

Related Questions