Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data attribute changes not detected with jQuery

I am changing the data-demo attribute of a div element and when I want to check it with in another event, it always shows me the initial value of it instead of the current value.

This is the code I am using:

$('#showValue').click(function(){
    alert($('.value').data('demo'));
});

$('.update').click(function(){
   $('.value').text('updated').attr('data-demo', 'updated');
});

Why is this happening?

Here's a fiddle with the example I am talking about: http://jsfiddle.net/f5Cpm/

Thanks.

like image 923
Alvaro Avatar asked May 02 '13 12:05

Alvaro


People also ask

How to get data attr in JavaScript?

JavaScript access To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written. In the above case setting article. dataset.

How to get prop value in jQuery?

The prop() method sets or returns properties and values of the selected elements. When this method is used to return the property value, it returns the value of the FIRST matched element. When this method is used to set property values, it sets one or more property/value pairs for the set of matched elements.

What is the data attribute?

In short, a data attribute is a single-value descriptor for a data point or data object. It exists most often as a column in a data table, but can also refer to special formatting or functionality for objects in programming languages such as Python.

What is a data attribute HTML?

Definition and Usage The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.


1 Answers

After the internal data is first initialized, it never goes back to the attribute to get or set the value, therefore updating the attribute will not update what is stored in .data() if you've already used .data on that element.

Read more here

like image 146
uross Avatar answered Oct 26 '22 19:10

uross