Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON object from HTML5 data-* attribute with JavaScript

Here's my HTML:

<input type="text" data-setup='{ "method" : "checkbox" }'>

Here's my JavaScript so far:

var a = document.querySelectorAll('[data-setup]')
for (var i=0;i<a.length;i++) {
    alert(a[i].getAttribute('data-setup'));
}

This then alerts:

ALERT: { "method" : "checkbox" }

But how can I access the JSON "method"? I want to essentially be able to alert the word "checkbox". Any help appreciated.

like image 879
Stephen Jenkins Avatar asked Jun 25 '13 15:06

Stephen Jenkins


2 Answers

JSON.parse would be the simplest way to create a proper object from that JSON:

for (var i=0;i<a.length;i++) {
    var obj = JSON.parse(a[i].getAttribute('data-psswrd'));
    alert(obj.method); //will alert what was in the method property
    console.log(obj); // should log a proper object
}

Of course this won't work in older browsers, so you'll need to shim it if you want that kind of browser support. Douglas Crockford has a shim here, and or course jQuery has a JSON parsing method if you were already using that utility.

like image 132
Adam Rackis Avatar answered Nov 02 '22 07:11

Adam Rackis


You need to use JSON.parse method for this:

var myJSON = JSON.parse( a[i].getAttribute('data-psswrd') );
alert( myJSON );

This is supported in all modern browsers and in IE8+.

If you need to support older browsers here is little hack. See Browser compatibility section.

like image 27
antyrat Avatar answered Nov 02 '22 06:11

antyrat