Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Javascript codes that are put in a textbox (in HTML5)

I have a textbox on my html page, I'd like to run the javascript code that people put it the textbox. How can I do that?

like image 372
Mark Avatar asked Dec 22 '22 17:12

Mark


2 Answers

You can create a new script dynamically like found here

Here's a quick example you can copy and paste into an html file and see it work. You'll notice that once called, the page reloads and stalls out. This could be solved by using ajax and a seperate page the executes the code and returns a value or string or whatever it is your code should return.

<html>
<head>
</head>
<body>
<script>
function doIt() {
    var headID = document.getElementsByTagName("head")[0];
    var newScript = document.createElement("script");
    newScript.type = "text/javascript";
    newScript.innerHTML = document.getElementById("textarea").value;
    headID.appendChild(newScript);
}
</script>

<textarea name="textarea" id="textarea">
alert("Alert");
</textarea>
<input type="button" value="Do It" onclick="doIt();" />
</body>
<html>
like image 85
Spidy Avatar answered May 21 '23 22:05

Spidy


You can use document.getElementsByName

<input name="textbox" type="text" />

<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox')[0].value)" type="button" value="Execute" />

something similar i found here

like image 33
ayush Avatar answered May 21 '23 21:05

ayush