0

I need to be able to paste something like this inside a textarea:

var cars = new Array(new Array(3), new Array(3));
cars[0][0] = 'FORD';
cars[0][1] = 'Focus';
cars[0][2] = 'Mondeo';
cars[1][0] = 'VOLKSWAGEN';
cars[1][1] = 'Golf';
cars[1][2] = 'Polo';
cars[1][3] = 'Lupo';

An afterwards being able to access cars array from my script as a common variable. Been trying with eval, but after googling I'm really scare of it. Can somebody help me?

0

1 Answer 1

1

You can attach arbitrary data to any html element with jquery .data() method.

So given a textarea like this:

<textarea id="txa"></textarea>

From jquery you could do:

var cars = new Array(new Array(3), new Array(3));
cars[0][0] = 'FORD';
...
$('#txa').data('myvar', cars);

And then retrieve it later with:

var arr = $('#txa').data('myvar');
alert( arr[0][0] ); //alerts FORD


UPDATE:
Now, based on your last comments, it seems what you just need is the eval() function to execute the javascript code you have in your textarea, like this:

code = $('textarea').val();
eval( code );
alert( arr[0][0] ); //alerts FORD

See working demo

Sign up to request clarification or add additional context in comments.

6 Comments

That sounds interesting, I'm going to check it out!
Hi again, I'm afraid I have explained myself poorly. Unfortunatelly what I currently have is some plain text coming from different external sources with different arrays declarations and I need a way to paste them on a text area and have it available as internal vars.
Trying to explain it even better, because I'm reading myself and I'm not able to understand me: I need to be able to transform javascript array declarations pasted inside a text area in a form into real arrays ready to be used.
Ok, based on your last clarification, I've updated my answer with an example to achieve what you want by using eval().
Remember to accept answer and upvote it if this finally solves your problem, I hope so :-) .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.