0

Is there a way to change the value of an html variable using jquery.

For instance,

  <div id="smile" data-count="2"></div>

how would I change the variable data-count to 3 using jquery

Kwaasi Djin
  • 125
  • 1
  • 11
  • That is not an "HTML5 variable" (there is no such thing). That's an HTML5 data attribute, and you can update it like any other attribute. – Felix Kling Jan 20 '14 at 01:43
  • possible duplicate of [setting a value dynamically for data attributes using jquery](http://stackoverflow.com/questions/7163234/setting-a-value-dynamically-for-data-attributes-using-jquery) – Felix Kling Jan 20 '14 at 01:46

2 Answers2

0
$('#smile').attr('data-count', 3);
Musa
  • 96,336
  • 17
  • 118
  • 137
Bowie
  • 992
  • 3
  • 10
  • 25
0

You can do:

$('#smile').data('count', 3);

or:

$('#smile').attr('data-count', 3);

You can store the data value in a variable and then increase it like this:

var data = parseInt($('#smile').attr('data-count'), 10);

$('#smile').attr('data-count', data+1);
Felix
  • 37,892
  • 8
  • 43
  • 55
  • 2
    Note that `$('#smile').data('count', 3);` doesn't change the attribute of the element, it only updates jQuery's internal data storage. – Felix Kling Jan 20 '14 at 01:43
  • is it possible to just increment data-count by 1 without having to retrieve the data and manually adding one and then updating? – Kwaasi Djin Jan 20 '14 at 03:01
  • what does the number 10 do? – Kwaasi Djin Jan 20 '14 at 03:18
  • @KwaasiDjin: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters. And no, it's not possible to increment the value without getting it first. – Felix Kling Jan 20 '14 at 03:20
  • @KwaasiDjin It's the `radix` which is a number (from 2 to 36) that represents the numeral system to be used, i.e. 2 for binary, 10 for decimal, 16 for hexadecimal. You can used @Felix Kling reference link for more details about it. – Felix Jan 20 '14 at 03:26