7

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>
user3266909
  • 83
  • 1
  • 1
  • 4

7 Answers7

9

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 );

Demo

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
4

Use:

$("#obj-details").attr('data-value');
Arunkumar
  • 5,150
  • 4
  • 28
  • 40
3
$('#obj-details').data('value');
Alien
  • 3,658
  • 1
  • 16
  • 33
3

If you looking the return data as a object, try like below.

var country = eval('(' + $("#obj-details").attr('data-value') + ')');

alert(country.city);
Jaison James
  • 4,414
  • 4
  • 42
  • 54
1

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
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

jquery.parseJSON(jquery("#obj-details").attr("data-value"));

minam.cho
  • 122
  • 1
  • 12
0

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)

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177