tim peterson
tim peterson

Reputation: 24305

Escaping quotes and html in a data- attribute JSON object

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>

Upvotes: 5

Views: 10760

Answers (1)

Julien Royer
Julien Royer

Reputation: 1429

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>

Upvotes: 8

Related Questions