简体   繁体   中英

how can I send to javascript console in browser code entered by user in textarea

I want to build a webpage for user to be able to practice code exercises. in javascript. and I'm looking for a way to execute the code on the browser session and display the user if there's any errors. I was wondering if by grabbing user text from textarea and executing it as part of a function will work. Here's what I got, but I haven't been able to send to console the user entered text.. any help thanks

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>JScript Page</title>
    <script>
      function jstest() {
        var text = document.getElementById("textArea").value;
        console.log(text);
      }
    </script>
  </head>
  <body>
    <h2>Enter your code here!</h2>
    <form  >
    <textarea rows="4" cols="50" id="textArea">
</textarea><br>
  <input type="submit" value="Submit" onclick="jstest()">
</form>
  </body>
</html>

What happens is that the form is being submitted and it makes the page to refresh and that's why you can't see the console.log . You can return false to prevent the form submission or remove the form at all.

 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JScript Page</title> <script> function jstest() { var text = document.getElementById("textArea").value; console.log(text); return false; } </script> </head> <body> <h2>Enter your code here!</h2> <form> <textarea rows="4" cols="50" id="textArea"> </textarea><br> <input type="submit" value="Submit" onclick="return jstest();"> </form> </body> </html> 

WITHOUT FORM (AND EVAL)

 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JScript Page</title> <script> function jstest() { var text = document.getElementById("textArea").value; try { eval(text); } catch (e) { if (e instanceof SyntaxError) { alert(e.message); } } } </script> </head> <body> <h2>Enter your code here!</h2> <textarea rows="4" cols="50" id="textArea">alert('some')</textarea><br> <input type="button" value="Submit" onclick="jstest();"> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM