Pabuc
Pabuc

Reputation: 5638

Access custom attributes via jquery

I need to access to the custom attribute or data of my link but I can't. My code is simple yet in repeater. I don't know if this is causing a problem. Here is the code:

 <a class="showAllComm" data-userid='<%# DataBinder.Eval(Container.DataItem, "USER_ID")%>' href="#sa">Show all comments</a>

Here is my click event:

$('.showAllComm').click(function(index, element) {
            var commId = $(element).data("userid");
 })

commId is undefined but I can see it in the source code that it has value of 1.

how can I access to the userId?

Thank you

Upvotes: 3

Views: 4610

Answers (2)

RSG
RSG

Reputation: 7123

The data method is not a shortcut for the attr method. It takes an element and an attribute, per the docs

Just use attr("data-userid")

Upvotes: 1

user113716
user113716

Reputation: 322462

Reference the element with this instead of the second parameter:

var commId = $(this).data("userid");

The arguments passed to an event handler are not the index and element as you'd have in .each().

By default, you just get a single event argument passed.

DEMO: http://jsfiddle.net/Jjbwd/

$('.showAllComm').click(function( event ) {

    alert( event.type ) // click

    var commId = $(this).data("userid");
});

Upvotes: 8

Related Questions