I am trying to update 'id' and 'selected' within data-options.
HTML:
<span class="re_highlight-feature" data-toggle="tooltip" data-animation="false" data-placement="top" title="" data-options="{'id':0,'name':'Appliance','value':'Dryer','selected':false}" data-original-title="Highlight Dryer">Dryer</span>
I am able to reference them and pass the correct values to my AJAX function.
JS:
$('.re_highlight-feature').click(function(e) {
e.preventDefault();
var feature = $(this);
var featureDislay = feature.text();
var featureData = feature.data('options');
feature.html('<i class="fa fa-refresh fa-spin fa-fw"></i><span class="sr-only">Loading...</span>');
$.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: {action:'highlightFeature', id:featureData.id, name:featureData.name, value:featureData.value, selected:featureData.selected},
success:function(json){
obj = JSON && JSON.parse(json) || $.parseJSON(json);
var recordID = obj.id;
if (recordID == 0){
featureData['id'] = 0;
featureData['selected'] = false;
} else {
featureData['id'] = recordID;
featureData['selected'] = true;
}
feature.html(featureDislay);
feature.toggleClass('mark');
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
});
Everything works except this:
if (recordID == 0){
featureData['id'] = 0;
featureData['selected'] = false;
} else {
featureData['id'] = recordID;
featureData['selected'] = true;
}
I haven't been able to figure out how to update those values within my original element.
Note that properties of data-*
at HTML
should have properties surrounded by double quotes to set data-*
attribute value as valid JSON
within HTML
document
.
data-options='{"id":0,"name":"Appliance","value":"Dryer","selected":false}'
for ability to define a JavaScript object at
var featureData = JSON.parse(feature[0].dataset.options);
If you are trying to update the actual HTML
you can use HTMLElement.dataset
, JSON.stringify()
, JSON.parse()
if (recordID == 0) {
featureData.id = 0;
featureData.selected = false
feature[0].dataset.options = JSON.stringify(featureData);
} else {
featureData.id = recordID;
featureData.selected = true;
feature[0].dataset.options = JSON.stringify(featureData);
}
Inspecting .re_highlight-feature
at DevTools
or Developer Tools
reveals that the data-*
attribute is updated at the HTML
document
.
var feature = document.querySelector(".re_highlight-feature");
var featureData = JSON.parse(feature.dataset.options);
console.log(featureData);
featureData.id = 1;
featureData.selected = true
feature.dataset.options = JSON.stringify(featureData);
console.log(JSON.parse(feature.dataset.options));
console.log(feature.outerHTML);
<span class="re_highlight-feature" data-toggle="tooltip" data-animation="false" data-placement="top" title="" data-options='{"id":0,"name":"Appliance","value":"Dryer","selected":false}' data-original-title="Highlight Dryer">Dryer</span>