1

I have a link that is changing some parameters dynamically based on activities on the page. The function for replacing the values seems to be working fine and I can see in the "elements" window in the chrome developer tools that it is being updated. However, when I try to read that value from another JS function, then it is as it has not been changed at all.

I have made a very simplified example of the issue:

<a href="#" id="a-delete-page" data-action="data/1/pageid/0/">
check data-action value</a>    
<a href="#" id="toggle">set new value</a>

<script>
$('#a-delete-page').click(test);
$('#toggle').click(toggleValue);

function toggleValue(){
    var newValue = '123';    
    $("#a-delete-page").attr('data-action',newValue);

    alert("new value set:"+newValue);  
}

function test(){
  alert($(this).data('action'));   
}
</script>

Try it here: http://jsfiddle.net/2hj3e/

First click "check data-action value" and you see the data-action parameter. Then click set new value (and you see it changes in the developer tool) and click "check data-action value" again. I would expect it to print 123, but it still prints "data/1/pageid/0/".

Could anyone help me understand this and also direct me on how to resolve this.

2
  • data object and data attribute is not the same thing. Only that jQuery on DOM load will parse data-* attributes to data object, but changing then data-* attribute will not update data object, see jsFiddle to fix your issue: jsfiddle.net/2hj3e/1 Commented Mar 6, 2014 at 17:25
  • It doesn't happen on DOM load, it happens the first time you call .data() on an element. In his jsfiddle, that happens when it calls updateUrlParameter with the old data. Commented Mar 6, 2014 at 17:32

2 Answers 2

3

jQuery only pulls in the values from the data- attributes the first time that you call .data(). After that, it essentially caches them, so even if you update or add another data- attribute, it doesn't get reflected in calls to .data(). If you want to update the data after that initial call, then you need to use .data('action', newvalue) to set it.

Source: http://api.jquery.com/data/#data-html5

Sign up to request clarification or add additional context in comments.

Comments

0

jQuery has some quirks with .data. If you are using .data to retrieve the value, also use it to set it.

$("#a-delete-page").data('action',newValue);

4 Comments

could it be that it's setting an object's property instead of the actual element attribute? I too noticed that setting data via jQuery doesn't update the document element with a data- attribute.
I think the problem was that attributes can only contain strings, and .data can contain an arbitrary object.
Good to know! you don't have any documentation on this other than api.jquery.com do you?
No, that's probably where I've got it from.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.