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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With