5

Using the HTML5 data- attribute, one can store JSON in HTML as shown in the HTML below. This works great with string key:value pairs but I can't figure out how to make the values include special characters or HTML.

The part of the JSON object that is giving problems is this: Can't vote on <b>own</b> review (also interested in more complicated HTML chunks like this: <span style="text-decoration:underline" own</span>. Here's a JSFiddle for the code below.

JS:

$('button').on('click', function () {
  var $this=$(this), data=$this.data('data');
     $('#output').html(data.message);
});

HTML:

<button type='button' data-data='{"type": "voting", "message": "Can't vote on <span style="text-decoration:underline" own</span> review"}'></button>
<div id='output'></div>
0

1 Answer 1

8

You need to escape the HTML and specifically in this example, & and the character used to quote the attribute value (either " or '):

<button type='button' data-data='{"type": "voting", "message": "Can&#39;t vote on <b>own</b> review"}'></button>

or:

<button type='button' data-data='{"type": "voting", "message": "Can&#39;t vote on <span style=&#39;text-decoration:underline&#39;>own</span> review"}'></button>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.