Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't update data-attribute value

Tags:

jquery

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?

like image 647
dev Avatar asked Jul 20 '13 13:07

dev


People also ask

How do you set the value of a data attribute?

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.

How do you update attributes in HTML?

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() .

What is data value attribute?

The HTML data value attribute is used to Specify the machine-readable translation of the content of the element.

What is an example of a data attribute?

Examples of attribute data include sorting and counting the number of blemishes in a particular product (defects), and the number of nonconforming pieces (defectives).


2 Answers

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...

like image 132
A. Wolff Avatar answered Oct 14 '22 08:10

A. Wolff


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) 
like image 21
Lucas Willems Avatar answered Oct 14 '22 07:10

Lucas Willems