0

I have a one span tag with data attribute, data-kr-id. On clicks of different items of the list, I update this span's data-kr-id attributes and it gets updated.

When for the first time I retrieve this(data-kr-id) value using jQuery's data method, I get the correct value. But from the subsequent time, I always get the same value as of the first time. But on using jQuery's attr function, I get the correct value. Can't figure out why.

CODE: Where I set the data-kr-id value:

$_applozicWtLauncherBtn.attr('data-kr-id', seller.UserId);

CODE: Where I retrieve the values:

 var topicId = $applozic(this).data("kr-id");
 topicId = $applozic(this).attr("data-kr-id");

In the above code where I retrieve values, using data method gives me old value(the value of the first item I retrieved), but using attr method gives me correct value.

UPDATE :

As informed by everyone, I was setting the data attributes with attr method and retrieving the value with data method. After using data method for setting the attribute, When I was retrieving the values, I was getting a getting empty string. After digging a bit deeper, I realized there are two different versions of the jQuery are being used here.

Sorry for the incomplete information and late update.

Community
  • 1
  • 1
kumarmo2
  • 1,381
  • 1
  • 20
  • 35
  • Because you're explicitly setting `data-kr-id`. `jQuery.data` – Adam Azad Jun 29 '18 at 03:48
  • can I see ther section wher you assign " $_applozicWtLauncherBtn " to your element – Rumesh Jun 29 '18 at 03:49
  • Why are you setting them with `attr`? `.data()` is designed to handle that for you. I might be misremembering, but I think jQuery actually stores the data in an object in memory rather than directly on the DOM like `.attr()`. https://api.jquery.com/data/ – mccambridge Jun 29 '18 at 03:54

2 Answers2

0

You set value only using attr, Second time when you set data-kr-id value using attr then data value remains same, so need to set value with data also

// With Attr
$_applozicWtLauncherBtn.attr('data-kr-id', seller.UserId);
// With Data
$_applozicWtLauncherBtn.data('kr-id', seller.UserId);
Jagjeet Singh
  • 1,564
  • 1
  • 10
  • 23
0

Actually jquery's .data() fetches value from the property (same as .prop()) not from attributes. Main difference is .attr() fetches data from HTML tag which you can see it will reflect on your HTML when you update it with .attr(). But when you use .prop() or .data() it will not reflect in HTML tag but it will update value in it's property for that HTML tag as per the DOM tree.

You'll find out more about difference property and attribute from here. Initially this property will set when your element is created. So for the first time your .data() and .attr() will work fine. When you update value from .attr() it will manipulate DOM but property will be remain same.

Karan
  • 12,059
  • 3
  • 24
  • 40