Correctly update the HTML data attribute, but the changes do not appear on the page

I have this HTML:

<input type="text" id="query" data-source="whatever"> 

I have some jQuery that successfully changes the data attribute, that is, "everything" changes to "test"

 $(function() { $('#query').data('source', 'test'); console.log($('#query').data()); }); 

but if I inspect the page using Chrome, the data attribute in the element has not been updated. I can print it in the console, but I can not check the new value! Very confusion Any ideas?

here is the violin

+8
source share
4 answers

Data is not stored in the element (use attr or prop for this). Instead, jQuery supports it in $ .cache.

+9
source

If you are doing something crazy, for example, using the data attribute to apply a style (no, it's not very crazy), you need both jQuery cache and DOM to update.

Change jQuery

 $element.data(key, value); 

which will not update the DOM to a method that executes as

 var data = function($element, key, value) { $element.data(key, value); $element.attr('data-'+key, value); } data($element, key, value); 

Note. I always put $ in front of jQuery variables if someone is confused.;)

+1
source

In your violin you have this code.

 $(function() { $('#query') = $('#query').data('source', 'test'); console.log($('#query').data()); }); 

which has an error ("Invalid left side in destination"), because $('#query') is a function call, and you check the .data('source', 'test') response to it.

Change it to

 $(function() { $('#query').data('source', 'test'); console.log($('#query').data()); }); 

it will work fine.

Take a look at http://jsfiddle.net/r5YV9/10/

0
source

Refer to the jquery documentation about data() please and you will see there:

Using the data () method to update data does not affect attributes in the DOM. To set the value of the data- * attribute, use attr.

So you should use

 $('#query').attr('data-source', 'test'); 
0
source

All Articles