1

Im trying to get data out of a data attribute using jquery.

Heres what I have:

<div id="x" data-foo="{top:'100', left:'40', width:'50'}">

and in javascript:

x = $('#x').data();

console.log( x.foo.top ) //undefined

Ive tried JSON parse as well, but I get errors about unexpected tokens then.

Tuan Ha
  • 620
  • 2
  • 8
  • 25
Jason Lough
  • 33
  • 1
  • 3

3 Answers3

2

You can get data with jQuery attr x = $('#x').attr('data-foo'); And then parse it to json like: var data = JSON.parse(x)

Elyas Esna
  • 625
  • 4
  • 19
  • `.data('foo')` gets the attribute value. No need for `attr`. –  Apr 03 '19 at 18:26
  • Same issue. The challenge is to set the data in the attribute with the HTML. It did get me thinking about how the string was formatted though. I think I have the answer, one sec to confirm. – Jason Lough Apr 03 '19 at 18:30
  • Yep, if you format the string properly, you can use it as a JSON object, otherwise you get errors trying to parse or access the keys. Proper string in my eample would be (note the use of quotes): '{"top":"100", "left":"40", "width":"50"}' – Jason Lough Apr 03 '19 at 18:32
1

Please arrange your code like this

 <div id="x" data-foo='{"top":"100", "left":"40", "width":"50"}'> 

 In JSON, Key will be double quote. 
MD. ABDUL Halim
  • 712
  • 3
  • 11
  • 32
  • @JasonLough Please go to the link and test it. https://jsfiddle.net/ahscse/gvu48Lqc/ – MD. ABDUL Halim Apr 03 '19 at 18:42
  • @JasonLough If this is the answer, click the checkmark to accept it. See https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –  Apr 03 '19 at 18:45
  • As this question has been downvoted most likely because of suggesting to use single instead of double quotes: [both are legit](https://stackoverflow.com/questions/2373074/single-vs-double-quotes-vs). I would recommend to stick to either single or double quote and use `"` inside your `data-foo` value, otherwise this may be a cause of problems if someone else has to maintain your code. – SaschaM78 Apr 03 '19 at 18:50
  • @JasonLough you can click Check mark (it will be selected) but not up or down Key – MD. ABDUL Halim Apr 03 '19 at 18:50
0

What you have in data-foo is the string for a Javascript Object Literal and not JSON

Firstly, you need your JSON formatted properly. See below.

<div id="x" data-foo='{"top":"100", "left":"40", "width":"50"}'></div>

Read more about that here.

https://medium.com/@easyexpresssoft/object-literal-vs-json-7a2084872907

Then, use JSON.parse() to get your data

var x = JSON.parse($('#x').attr("data-foo"));
alert( x.top );

Hope it helps

user2993497
  • 525
  • 1
  • 7
  • 21