How can I get data-value
country using jQuery? I need this in variable:
var country = ...;
HTML:
<a id="obj-details" data-value="{city:'berlin', street: 'mozart', postal_code: '55555', country: 'DE'}">test</a>
How can I get data-value
country using jQuery? I need this in variable:
var country = ...;
HTML:
<a id="obj-details" data-value="{city:'berlin', street: 'mozart', postal_code: '55555', country: 'DE'}">test</a>
To read data-value
attribute use below jQuery :
$("#obj-details").data('value');
and to read country
from the data-value
use below jQuery :
var value = $("#obj-details").data('value');
var obj = eval('(' +value + ')');
var country = obj.country;
alert(country );
If you looking the return data as a object, try like below.
var country = eval('(' + $("#obj-details").attr('data-value') + ')');
alert(country.city);
Try to use .data(key)
to retrieve that value,
var obj = JSON.parse($("#obj-details").data('value')); //Entire object
var country = obj.country; //Country value
Try object
at data-*
attribute utilizing double ""
quotation marks.
html
<a id="obj-details"
data-value='{"city":"berlin"
, "street": "mozart"
, "postal_code": "55555"
, "country": "DE"
}'>test</a>
js
var obj = JSON.parse($("#obj-details")[0].dataset.value);
var country = obj.country;
$("#obj-details").text(country);
jsfiddle http://jsfiddle.net/guest271314/6LcfS/
See also How can you parse NON wellformed JSON (maybe using jQuery)