user6911589
user6911589

Reputation:

Using eval() to run HTML code

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:

Upvotes: 1

Views: 2499

Answers (3)

Anand G
Anand G

Reputation: 3210

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!

Upvotes: 2

Flight Odyssey
Flight Odyssey

Reputation: 2287

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.

Upvotes: 0

Thach Nguyen
Thach Nguyen

Reputation: 76

  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);

Upvotes: 0

Related Questions