GETah GETah - 7 days ago 7x
Javascript Question

JQuery data function returns the wrong value

I have an input text which one of its

attribute is changed on the fly as soon as my view model changes ( thanks to Knockout).
The binding is done as follow:

<input data-bind="attr:{'data-customitem': customItemId}" />

Somewhere in my view model, I have a function which accesses the input and retrieves the
attribute value.

The first time the input is bound, it gets an id, say
. So the HTML looks like this:

<input data-bind="attr:{'data-customitem': customItemId}" data-customitem='X'/>

Then my model changes and knockout updates the attribute value to
. The HTML now looks like this:

<input data-bind="attr:{'data-customitem': customItemId}" data-customitem='Y'/>

The problem now is:



Why is jQuery data function returning an old value of the data attribute? Is there any caching going on behind the scenes?


There is a different between the jQuery's data function and the attr function. The data function is binded to the element (not necessary to the data attribute). If an element has data-X='val' you can use both jquery's data function and the attr function to get the value:


However - in case you change the data (using the data(...) function) - to get the new value you must use the data function (this change will not affect the value of the attribute), and the opposite is the same - if you change the value using the attr function - it will not affect the values of the data() function.

Here is an example:

$(function() {
  $('#btn1').click(function() {
    console.log('value using data function: ' + $('#d1').data('name1'))
    console.log('value using attr function: ' + $('#d1').attr('data-name1'))
  $('#btn2').click(function() {
    $('#d1').data('name1', 'new value - using data');
  $('#btn3').click(function() {
    $('#d1').attr('data-name1', 'new value - using attr');
<script src=""></script>
<div id="d1" data-name1="abc"></div>
<button id="btn1">Get Values</button><br />
<button id="btn2">Change Values using data function</button><br />
<button id="btn3">Change Values using attr function</button><br />

The changes you are doing (using data-bing="attr:{...}") don't affect the values of the jQuery's data function.