Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a data attribute(with special characters) to a dom element using jquery

I am trying to add a data attribute to a html element. The data attribute(data-description) can contain special characters like apostrope.

InsertHtml = InsertHtml + '<tr id="DashboardRow0" data-description=\'' + JSON.stringify(data[0])+ '\'><td>' + </td></tr>';
htmlElement.append(InsertHtml);

The code to access this data is given below...

var $row = $("#DashboardRow0");
var jsonData = eval('(' + $row.attr('data-description') + ')');

But the problem is...If there is a single apostrophe within JSON.stringify(data[0]) data..the browser replaces it with a " effectively terminating the string.

Is there any know solution to adding data attributes with special characters to nodes?

like image 881
Whimsical Avatar asked Dec 19 '25 05:12

Whimsical


2 Answers

try to escape data before stringify

data[0].myProblemField = escape(data[0].myProblemField)
JSON.stringify(data[0])

<edit>
or better

 for(var prop in data[0]) if(typeof(data[0][prop]) == "string") 
   data[0][prop] = escape(data[0][prop]);

</edit>

and afterwards

var jsonData = eval('(' + $row.attr('data-description') + ')');
jsonData.myProblemField = unescape(data[0].myProblemField)
like image 80
rbhro Avatar answered Dec 20 '25 18:12

rbhro


Not entirely sure whether this'll help you (i.e. whether this is all happening in the same document), but have you considered using jQuery's .data()? It won't have these problems, as the data is stored as a variable.

like image 38
Pekka Avatar answered Dec 20 '25 17:12

Pekka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!