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>
4
  • jquery.data('value') Commented Jul 4, 2014 at 8:50
  • $('#obj-details').data('value') Commented Jul 4, 2014 at 8:51
  • Find detailed explanation here: stackoverflow.com/questions/22753629/… Commented Jul 4, 2014 at 8:53
  • @user3266909, please check my answer. this gives you country value as DE Commented Jul 4, 2014 at 9:13

7 Answers 7

10

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

Sign up to request clarification or add additional context in comments.

Comments

4

Use:

$("#obj-details").attr('data-value');

Comments

3
$('#obj-details').data('value');

Comments

3

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

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

alert(country.city);

Comments

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

1 Comment

alert(obj); works fine but alert(obj.country);not. It displays undefined
0

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.