Kleber S.
Kleber S.

Reputation: 8240

Jquery: help to get values from data attributes

I have the following markup

<a href='#' id="remove_user_from_group" data-user-id="a9a4ae36-c6cd-11e1-9565-910084adb773" data-group-id="e4d66f80-d046-11e1-89b6-16f96811a1bd">x</a>

And I want to get the data from user-id and group-id.

For now, I have tried:

$this = $(this);
$("#remove_user_from_group").live('click', function() {
    var userid = $this.data('user-id');
    var groupid = $this.data('group-id');
    alert(userid);
    alert(groupid);
});

which pops me 2 alerts with undefined values.

What am I missing here?

Upvotes: 0

Views: 684

Answers (2)

j08691
j08691

Reputation: 207901

Put $this = $(this); inside your click function. Or, change the function to just:

$("#remove_user_from_group").live('click', function() {
    var userid = $(this).data('user-id');
    var groupid = $(this).data('group-id');
    alert(userid);
    alert(groupid);
});

jsFiddle example 1 and jsFiddle example 2

Also as an aside, live() has been deprecated in favor of on().

Upvotes: 4

Horen
Horen

Reputation: 11382

You need to convert the object in the function to a Jquery Object by changing $(this) instead of $this on line 3 and 4

Upvotes: 1

Related Questions