Although there are some examples of this on the web, it does not seem to work correctly. I can't figure out the problem.
I have this simple HTML
<div id="foo" data-num="0"></ div> <a href="#" id="changeData">change data value</a>
Every time I click the link "change data value" I want to update the data value of data-num. For example, I need it to be 1,2,3,4,... (plus 1 every time I click the link)
what I have is
var num = $('#foo').data("num"); console.log(num); num = num+1; console.log(num); $('#foo').attr('data-num', num);
The value changes one time from 0 to 1 every time. I can't make it incremental. Any suggestions on what I'm doing wrong?
To set an attribute and value by using a function using this below syntax. $(selector). attr(attribute,function(index,currentvalue)) ; To set multiple attributes and values using this below syntax.
setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .
The HTML data value attribute is used to Specify the machine-readable translation of the content of the element.
Examples of attribute data include sorting and counting the number of blemishes in a particular product (defects), and the number of nonconforming pieces (defectives).
Use that instead, if you wish to change the attribute data-num of node element, not of data object:
DEMO
$('#changeData').click(function (e) { e.preventDefault(); var num = +$('#foo').attr("data-num"); console.log(num); num = num + 1; console.log(num); $('#foo').attr('data-num', num); });
PS: but you should use the data() object in virtually all cases, but not all...
THE ANSWER BELOW IS THE GOOD ONE
You aren't using the data method correctly. The correct code to update data is:
$('#foo').data('num', num);
So your example would be:
var num = $('#foo').data("num") + 1; console.log(num) $('#foo').data('num', num); console.log(num)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With