Adding a script as a string to a textarea value

The question is pretty clear. I want to change the value of textarea using jQuery. What am I doing:

$( '#embedcode' ).val( "<script id='embed_1' src='/javascripts/test.js' type='text/javascript'></script>" ); 

What is the right way to do this. I get an error message:

 Uncaught SyntaxError: Unexpected identifier 

How to do what I want to add as a string, not a script.

+4
source share
4 answers

Here you go:

Create your line like this:

 $('#embedcode').val("<script id='embed_1' src='\/javascripts\/test.js' type='text\/javascript'><\/script>"); 

Check out this JsFiddle I made for you:

http://jsfiddle.net/KB9Qn/14/

+4
source

Your code is working fine. Here's a live demo: Click here.

You need to check the line number where you get this error.

edit: I just thought. If your html markup has an error (possibly a closed text area), the script can be evaluated as a script tag, not text. Check it. Here is a live example of an html error that will cause your problem. Press here.

Update: I believe I know exactly what the real problem is. Other posts recommend that you avoid '<' and '>', but this is only necessary if the javascript you use is actually located in the html file (or html generated by the server) and not in the js file where he belongs. In the js file, this, of course, will be the line as you wrote it, but the html file sees it as markup, although it is not intended. This is an example of why you should follow best practices and store javascript in a js file.

+3
source

You need to get away from "<" and ">".

 $('#embedcode').val("\<script id='embed_1' src='/javascripts/test.js' type='text/javascript'\>\</script\>"); 

Demo

+3
source

delete < and > in the line with \

+2
source

Source: https://habr.com/ru/post/1500232/


All Articles