Klapsius
Klapsius

Reputation: 3359

JQuery get value from dynamically created href

I have a dynamical hyperlink generated via jQuery. And I don't know how to get value of this element:

<a href="?t-action=' + data[i].pk_id + '" class="transfer">'+ '\ <img src="../images/like.png"...

But if i'm using alert($(this).attr('href')); The output is ?t-action=12345 Is it posible to get only 12345?

Upvotes: 1

Views: 205

Answers (2)

Natsathorn
Natsathorn

Reputation: 1528

You can add an attribute to a tag. In this case I use data-.

like this :

<a href="?t-action=' + data[i].pk_id + '" data-number="+data[i].pk_id+" class="transfer">

Then you can get than value by

$(this).data('number');

You can change the tag data-number to something else you prefer. Then update string inside .data() to be the same.

If you use data-foo in your jquery have to be $(this).data('foo');.

https://api.jquery.com/jquery.data/

Upvotes: 2

Marcelo Sader
Marcelo Sader

Reputation: 351

I sugest you to use data attributes.

<a href="?t-action=' + data[i].pk_id + '" data-pkid="data[i].pk_id" class="transfer">'+ '\ <img src="../images/like.png"...

Then, to output id use this:

alert($(this).data('pkid'));

Upvotes: 0

Related Questions