Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set data-id to HTML element

I'm searching for this sometime. Found this old article and this. But not working for me.

My Problem is : I cannot set incremented data-id to HTML Element via jQuery. I'm able to alert the same, But I failed to set in HTML. There is no change in the element if I inspect.

jQuery

$(document).ready(function() {    
   $("#search").click(function(){      
   var num = $(this).data('id');    
    num++; 
    $("span").text(num);
    $(this).data('id', num);
   });    
 });

I tried this also

$(this).data('id') === num;

Here is a jsFiddle Demo

I'm using v1.9.1 and no error in console. Its great if anyone can find the issue.

like image 503
Surjith S M Avatar asked Jan 07 '14 12:01

Surjith S M


People also ask

How do you set data to an element in HTML?

Creating an HTML Data Attribute Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.

How do I get the data ID of an element?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

What is data ID attribute in HTML?

The id attribute specifies a unique id for an HTML element. The value of the id attribute must be unique within the HTML document. The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id.


3 Answers

All other answers are correct - fixing 'val' to val - that of course solves the NaN issue.

The problem however is:

I cannot set incremented data-id to HTML Element via jQuery. I'm able to alert the same, But I failed to set in HTML. There is no change in the element if I inspect.

jQuery uses internal representation (1) for data. If you want to see data-id in inspector you need to use: $(this).attr('data-id', num);


(1) "Internal represenation":

All data is stored inside a property of the jQuery object named cache. Log the contents of $.cache in your console to see all data and events associated with any DOM element.

See: https://stackoverflow.com/a/4385015/775359

like image 108
Mars Robertson Avatar answered Oct 22 '22 06:10

Mars Robertson


The problem is in this line.

$(this).data('id', 'num');

num should be a variable, not a string.

Change it to this and it will work fine:

$(this).data('id', num);
like image 2
James Hibbard Avatar answered Oct 22 '22 07:10

James Hibbard


Try this to get:

$(this).attr('data-id');

and this to set attribue:

$(this).attr('data-id', num);
like image 2
Oleg Avatar answered Oct 22 '22 08:10

Oleg