Reputation: 35349
I need to pass data from an HTML element and serialize it. At the moment I can do it by naming each individual attribute in the HTML tag. But It seems verbose and complicated.
<a data-type="2" data-post="101" data-parent="100">Up</a>
var myData = $(this).data("type")+$(this).data("parent")+$(this).data("post")
Can I pass all of the data with a single call instead of naming each individual attribute? For example:
var myData = $(this).data(all the attributes go here in some sort of string/serialized string)
Upvotes: 0
Views: 68
Reputation: 816580
Note: This requires jQuery 1.4.4
You could do:
var myData = $(this).data();
var str = '';
for(var i in myData) {
if(myData.hasOwnProperty(i)) {
str += myData[i];
}
}
// generates "2101100"
But note that data()
might return more then just the HTML data attributes.
Depending on how you want to serialize the data, JSON.stringify might also be ok for you (which generates a JSON string):
var myData = $(this).data();
var str = JSON.stringify(myData);
// generates: {"type":2,"post":101,"parent":100}
Upvotes: 4