turbo2oh
turbo2oh

Reputation: 2879

how to access json data attribute

I have a data-attribute for several element that I'm using to store an ID and a value for each picklist values for each element. These will all be used to populate one field in a modal if one of the elements is edited.

I've added the ID and name for each option for each element into the data attribute like so:

{id:a0Dd000000RT1dOEAT,name:aa},{id:a0Dd000000RT1dPEAT,name:bb},   {id:a0Dd000000RT1dQEAT,name:cc},{id:a0Dd000000RT1dREAT,name:dd},{id:a0Dd000000RT1dSEAT,name:ee}

These represents 5 picklist options for one of the elements.

What is the syntax to extract each one? I've tried versions of:

$('#elementID').data('picklistvalues')[0].id

and its not working, any suggestions? I'm obviously far from a javascript expert.

Upvotes: 0

Views: 541

Answers (2)

Matt Ball
Matt Ball

Reputation: 359846

You need to JSON.parse() the value that .data() returns; then you can work with the value as a full JavaScript object.

var data = $('#elementID').data('picklistvalues');
// the attr value in the OP is not quite valid JSON
var obj = JSON.parse('[' + data + ']');
var id = obj[0].id;

Upvotes: 1

Jon Trauntvein
Jon Trauntvein

Reputation: 4554

It looks to me that you need to place quotes around the "id" values. These are not quite numbers and will not likely parse as anything but strings.

Upvotes: 1

Related Questions