Talen Kylon
Talen Kylon

Reputation: 1968

Executing code from a text area

I have a page that accepts Javascript code in a text area. I would like to run that code when the user presses the run button.

Is the following possible:

var programFunction = new Function(document.getElementById('program').value);

<button type="button" onclick="programFunction">run</button>

Let's say the textarea program has the following in it:

document.getElementById('program').value = 'Tested';

When I try to test this myself, I don't get any errors but I also don't get any output.

Upvotes: 1

Views: 198

Answers (2)

Felix Kling
Felix Kling

Reputation: 816462

There are a couple of things wrong in your code:

  • It seems like you try to access the content of the textarea before it got a value.
  • You don't run the function you created.

You have to retrieve the value of the texarea when the button is pressed, not before. Still using Function, it would look like:

<script>
function runCode() {
    var source = document.getElementById('program').value;
    var func = new Function(source);
    func();
}
</script>
<button type="button" onclick="runCode()">run</button>

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

You need your "run" button to process and run the code.

At its simplest, it's just:

onclick="eval(document.getElementById('program').value);"

Note that in this case, eval is perfectly okay provided that the value of the program field can only come from the user's own input, and not anyone else's.

Upvotes: 4

Related Questions