Question

I have the following element:

<div id="car" data-details='{ "color":"blue", "price":2000" }'></div>

I would like to change the property "price" using jQuery or JS:

Please check out this JSfiddle: http://jsfiddle.net/mLuz9/

I've tried:

$("#car").attr("data-details", '{"color" : "red", "price": 5000}');

but this requires the "color" to be set at the same time, I only want to set the "price" property.

Was it helpful?

Solution

Pull your JSON out of the data attribute to a variable, edit the variable, and re-set the attribute with your the updated variable.

Something like this should work:

<div id="car" data-details='{ "color":"blue", "price":2000 }'></div>

// Pull the info from the data-details attribute into a variable called 'details'
var details = JSON.parse($('#car').attr('data-details'));

// Change the price property in our variable
details.price = 5000;

// Write the variable version of details back to the data-details
// attribute on the DOM element
$('#car').attr('data-details', JSON.stringify(details));

$("html").append($("#car").attr("data-details"));

An updated version of your fiddle: http://jsfiddle.net/mLuz9/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top