1

In my code, i need to pass the value present in instance variable to javascript, and then use that value to set onto textarea.

$('textarea.myclass').val('<%= @text_value %>');

But if the variable @text_value contains \n (this is\n demo) then, its leads to javascript error and the page shows exactly as this, separated by space in between,

$('textarea.myclass').val('this is 
   // error message over here 
demo');

Any way i can handle this ?

2 Answers2

1

I also faced such situation, and i just escaped the \ to \\, so finally \n to \\n, \r to \\r

$('textarea.myclass').val('<%= @text_value.gsub("\r","\\r").gsub("\n","\\n") %>');

Hope this corrects you error too.

Ashis Kumar
  • 6,494
  • 2
  • 21
  • 36
1

The best answer I can come up with is to go for a variable. Without testing, this may be answer you are looking for:

var newline = "\n";
$('textarea.myclass').val('this is '+newline+' demo');

As SilverBlade suggested, maybe a double backslash would do the trick.

davewoodhall
  • 998
  • 3
  • 18
  • 43