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.
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.
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.
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.
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
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);
Try this to get:
$(this).attr('data-id');
and this to set attribue:
$(this).attr('data-id', 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