1

I am trying to do a "Try-it yourself" editor but without using frames. So I added 2 textareas, one for code and one to show the result. I also added a "Run" button. I wrote the following function to execute the code in the first text area and show the result in the second text area:

function RunCode() {
var Code= document.getElementById('code').value;
document.getElementById('result').innerHTML= eval(Code);
}

But all i get in the result text area is : undefined. Sorry for my stupid questions but I am really a beginner. So:

  • Does the eval function works only on javascript code?

  • Is it right to do the result part as a text area?

3
  • 2
    1) Yes; and 2) No Commented Mar 14, 2018 at 5:01
  • HTML is markup, not code (as the name says), and it cannot be run? What are you trying to do? What input did you enter in that textarea that did cause a problem? Commented Mar 14, 2018 at 5:01
  • 2
    if you are writing HTML In the first textarea and expecting the result in the second textarea, this will not work. Instead of second textarea you can use other element like 'div'. innerHTML is not working for textarea Commented Mar 14, 2018 at 5:10

3 Answers 3

2

Does the eval function works only on javascript code?

Yes, It only works on JavScript code. When the JavaScript code is written as a string, to execute that code we use eval() And this is only applicable to JavaScript. We don't use eval() in HTML since the HTML on browser works even if it is a string

eg,

function looseJsonParse(obj) {
  return eval(obj);
}
console.log(looseJsonParse(
  "{a:(4-1), b:function(){}, c:new Date()}"
))

Is it right to do the result part as a text area?

NO, <textarea></textarea> is a input element, which means it contains the value. Inner HTML works on other elements.

So for above, document.getElementById('result').val = Codeshould work. Note: If the value contains HTML then it will be treated as text and will not execute on the browser.

Bonus: Defining a variable with Capital letter is bad practice. Best practice says the variable should start with a small letter and it can be camel case.

Footnote: JavaScript eval() && textarea value

I hope this helps!

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

1 Comment

Thank you SO much! You've cleared up everything to me ! I really appreciate it !
0
  1. Make sure your code in "code" textarea return a value. And make a call if you define a function. E.g. try this in your "code": function a() { return 1 }; a();
  2. Should be document.getElementById('result').value = eval(Code);

Comments

0

Yes, eval works only on JavaScript code. To render your code as HTML, just assign it to innerHTML without the eval:

document.getElementById('result').innerHTML=Code;

To show the result, you should use a div, not a textarea.

1 Comment

No, innerHTML on a <textarea> does not work