Reputation: 4386
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
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
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 "
s which is pretty horrible:
e.g.
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}";
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