guub guub - 1 year ago 88
jQuery Question

Add attribute with JSON value

I want to add and store json in a

attribute via jQuery.
Problem is: when I add the attribute containing the json and escaped double quotes, it's added with the exact
and not the escaped double quotes.


<div data-myjson="{&quot;number&quot;:&quot;1&quot;}"></div>

Expected: Browser should treat
as double quotes and not as plain characters

<div data-myjson="{"number":"1"}"></div> // with escaped inner quotes

My jquery

$("div").attr("data-myjson", "{&quot;number&quot;:&quot;1&quot;}");

How can add actually escaped double quotes in the HTML itself?

Answer Source

Unless I'm misunderstanding, if the text containing the &quot; is a plain string as described above, the how about decoding it using:

var str = '{&quot;number&quot;:&quot;1&quot;}';
$("div").attr("data-myjson", $('<div/>').html(str).text());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download