Sébastien Gicquel
Sébastien Gicquel

Reputation: 4386

HTML5 data-attributes : How to modify array of data attached to DOM element?

I try to modify some HTML5 data-attribute with jquery.

I know how to do when it is simple like this :

<div id="element" data-options="HelloWorld"></div>

//Modify with jQuery :
$("#element").data("options","Bye Bye");

But in my case, i would like to modify a more complexe data-options (it's a joomla module).

data-options is organized like this with an array of datas :

data-options="{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"red","popup":1},{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"blue","popup":2}"

How can i select and modify only icon for example ?

Upvotes: 0

Views: 2415

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

You can use the function overload of jQuery.fn.data

$('#element').data('options', function(data){
   var obj = JSON.parse(data);
   obj.forEach(function(o){
       o.icon = "some other color";
   });
   return JSON.stringify(obj);
});

The above works assuming you have the following as your data.

'[{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"red","popup":1},{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"blue","popup":2}]'

To properly declare the json, you can put 'em in '' instead of "" which will save you from the headache of escaping double quotes.

Upvotes: 2

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

From comment: You will simply need to convert it from a string to an object using JSON parsing. The double-quotes are going to cause you grief though.

 var values = $.parseJSON($('#element').data('options'));

One only way to include a JSON literal in a standard HTML attribute is by encoding the "'s to &quot;s which is pretty horrible:

e.g.

data-options=";{&quot;title&quot;:&quot;Test&quot;,&quot;lat&quot;:&quot;48.6069129&quot;,&quot;lng&quot;:&quot;7.7612831&quot;,&quot;icon&quot;:&quot;red&quot;,&quot;popup&quot;:1},{&quot;title&quot;:&quot;Test&quot;,&quot;lat&quot;:&quot;48.6069129&quot;,&quot;lng&quot;:&quot;7.7612831&quot;,&quot;icon&quot;:&quot;blue&quot;,&quot;popup&quot;:2}";

or you can use single quotes for the delimiting (while not standard this will work on most browsers):

data-options='{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"red","popup":1},{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"blue","popup":2}'

Upvotes: 1

Related Questions