Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 706
tim peterson Avatar asked Feb 19 '23 06:02

tim peterson


1 Answers

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>
like image 170
Julien Royer Avatar answered Feb 21 '23 01:02

Julien Royer