Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I have a JSON code inside a textarea and I want to get it and work with it as it is exist in my website.
This is the textarea code :
<textarea>
var settings = [
"id" : "post_thumbnail",
"name" : "Default Post Thumbnail",
"desc" : "The image src that you want to use for non-thumbnail posts.",
"type" : "text",
"std" : "http://lorempixel.com/640/300/"
</textarea>
I tried this but unfortunately it work only if the code exist in the website not in textarea because I get this error :
Uncaught ReferenceError: settings is not defined
for( var i = 0; i < settings.length; i++){
var setting_id = settings[i].id,
setting_name = settings[i].name,
setting_desc = settings[i].desc,
setting_type = settings[i].type,
setting_std = settings[i].std;
$('body').html(setting_id +'<br>'+ setting_name +'<br>'+ setting_desc +'<br>'+ setting_type +'<br>'+ setting_std);
This is a live demo : http://jsfiddle.net/tauv0or1/
–
–
The value of textarea
does not get parsed as JavaScript. Instead, change the value to valid JSON:
<textarea>
"id" : "post_thumbnail",
"name" : "Default Post Thumbnail",
"desc" : "The image src that you want to use for non-thumbnail posts.",
"type" : "text",
"std" : "http://lorempixel.com/640/300/"
</textarea>
And tweak your JavaScript to use JSON.parse
on the value:
var field = document.getElementById("the_textarea");
var settings = JSON.parse(field.value);
Because the user can enter arbitrary information into the textarea, you might want to wrap JSON.parse
in a try-catch block, and alert the user to a syntax error:
var settings = null;
try {
settings = JSON.parse(field.value);
catch (error) {
if (error instanceof SyntaxError) {
alert("There was a syntax error. Please correct it and try again: " + error.message);
else {
throw error;
You need to eval the text first to actually run it as javascript:
eval($('textarea').text());
http://jsfiddle.net/tauv0or1/1/
Alternatively, you can parse it as JSON, but you need to edit the contents of the textarea first:
var settings = JSON.parse($('textarea').text());
http://jsfiddle.net/tauv0or1/2/
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.