0

I must have misunderstood, but I thought that the data-value of a HTML-element changes when calling the jQuery .data() function:

<div id="empty_column_0" data-name="empty_column_0" class="settings_toggle toggle-success inline-toggle" data-target="column_0" data-value="0"></div>

When I "toggle" this element, the data-value must change from 0 to 1 and vice versa.

I do this with:

$('.settings_toggle').on('toggle', function (e, active) 
{
    var that = $(e.target);  
    //Change the data value of the element
    if(active) {var bool = 1;} else {var bool = 0;}
    that.data('value', bool);
    console.log(that.data('value'));
});

The value changes in the console but not in the HTML? Is this how it is suppose to work?

PIDZB
  • 903
  • 1
  • 15
  • 38
  • Please see ["Should questions include “tags” in their titles?"](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not"! –  Nov 24 '15 at 09:59
  • this might be helpful http://stackoverflow.com/questions/10864353/on-toggle-working-together – Kaushik Nov 24 '15 at 10:00
  • I will leave the tags out next time:) – PIDZB Nov 24 '15 at 10:26

2 Answers2

4

This is by design. jQuery data() does not update the data- HTML attributes. If you wish to update the HTML attributes you'll need to use:

that.attr('data-value', bool);
SlashmanX
  • 2,489
  • 18
  • 16
  • @UnknownUser - Yes, and it doesn't update HTML `data-` attributes automatically like I stated and the OP asked... – SlashmanX Nov 24 '15 at 10:04
  • @Shomz What? The HTML attributes are not updated in that JSFiddle you linked... And the docs don't mention updating the HTML attributes at all – SlashmanX Nov 24 '15 at 10:06
-1

You code could work, please see the link to understand the difference between .data() and .attr():

  1. https://api.jquery.com/data/#data1

The .data() method allows us to attach data of any type to DOM
elements in a way that is safe from circular references and therefore from memory leaks.

  1. jQuery Data vs Attr?
Community
  • 1
  • 1
Sabrina Luo
  • 3,810
  • 4
  • 16
  • 35