DecoK
DecoK

Reputation: 145

inject JS code into a textarea

I am trying to show some JS code in a textarea. The code is generated with JS so I am injecting it into the textarea with JS. However, using the <script> tags, causes the script to execute. I thought using &lt; would solve this, but this is simply displaying &lt; instead of <.

Any suggestions how I can do this?

$('myTextarea').set('value', '<script>alert('do something');</script>');

Upvotes: 0

Views: 4330

Answers (2)

xdazz
xdazz

Reputation: 160843

Just separate the script tag into two.

$('myTextarea').val('<script>alert("do something");</scr'+'ipt>');

Upvotes: 1

Matt
Matt

Reputation: 75317

The next </script> after the opening <script> block closes the script block; whether it's contained with a JS string or not.

To fix you can either split the </script> like so;

$('myTextarea').set('value', '<script>alert('do something');</scr' + 'ipt>');

Or like this (less common, but works, and probably more correct);

$('myTextarea').set('value', '<script>alert('do something');<\/script>');

Furthermore, you also need to fix your quotes;

$('myTextarea').set('value', '<script>alert(\'do something\');<\/script>');

You can see this now working here: http://jsfiddle.net/pK9SK/

Upvotes: 0

Related Questions