0

I'm trying to create an input where someone can write javascript in a text area. After they click a button, I load the script they wrote in the text area and insert it into an html div that will be saved (saving this and other html elements as a custom created page basically)

However, when I insert the javascript into the div with jquery, it just runs the script, but does not insert the content. Is there a way to get the code to both run and copy over into the html so I can save what was written?

Edit: Here's an example:

HTML:

JS: (Jquery) $('#myDiv').html('window.alert("test")');

Pops an alert window up, $('#myDiv').html() = "", div is still empty.

I am looking for a way to insert the script text into the div, THEN run it without losing the script from the HTML.

Ivan Mayes
  • 125
  • 1
  • 8

2 Answers2

0

If you escape all the html (including the script tags) it won't run the javascript. If you do want to render all the other html entered in the textarea, you can just escape the script tag only. so the html becomes something like this:

<p>Just a paragraph</p>
&lt;script%gt;
    alert('this js does not run');
&lt;/script%gt;
<b>This is really bold</b>
timing
  • 6,340
  • 1
  • 17
  • 16
0

When inserting javascript to div tag you need to escape the characters. Here is the link showing a function that can do the escaping, Convert special characters to HTML in Javascript , look at the second reply having HtmlEncode function.

Community
  • 1
  • 1
Amit Bhagat
  • 4,182
  • 3
  • 23
  • 24