0

Possible Duplicate:
How to escape apostrophe or quotes on a JSP ( used by javascript )

I have a problem setting the value of a textarea element with jquery's val().

Basically, I have a JSP file which receives a string parameter called 'text'.

Java code:
String text = (String) request.getParameter("text");

Now I want my textarea element to receive this text:

Javascript code:
$('#textarea_id').val('<%=text%>');

It works when my text doesnt contain single quotes (and possibly other chars).

For example, for text =

test'

this error happens:

Uncaught SyntaxError: Unexpected token ILLEGAL
$('#textarea_id').val('test'');

I hope you guys understand. I need a way to encode this value... i tried using escape so the quote is replaced by %27, but after unescaping its replaced again and the error happens.

Thanks!

Community
  • 1
  • 1
Fabio K
  • 1,297
  • 4
  • 13
  • 24

3 Answers3

1

You're getting the error because Javascript is using the ' character to determine where your string ends. To include a literal quote in your string, escape the quote with a backslash.

$('#textarea_id').val('test\'');
Paul Alan Taylor
  • 10,474
  • 1
  • 26
  • 42
0

You need to escape the single quote with the Java code. The final output should look like

.val('test\'')
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • So I have to escape my Java string before setting its value in the textarea? Think i got it... i'll try thanks! – Fabio K Oct 17 '12 at 17:05
0

it should be

$('#textarea_id').val('test \' ');
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
MimiEAM
  • 2,505
  • 1
  • 26
  • 28