Reputation: 1968
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
Reputation: 816462
There are a couple of things wrong in your code:
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
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