0

I need to set a textarea value with a paragraph that's coming from a database.

$("#body").val('<%= @letter.body %>');

The code above works when @letter.body is just simple text, but it fails when there's newlines or anything else fancy in that field. How can I get the whole paragraph to render properly in my textarea, including any newlines, bullets, etc that might be included?

alex
  • 479,566
  • 201
  • 878
  • 984
sscirrus
  • 55,407
  • 41
  • 135
  • 228
  • Fails how? JavaScript error or the newlines don't show up? – alex Jul 19 '11 at 00:51
  • @alex - the code doesn't function if there are any `\n` characters (the JavaScript fails). I'm sure it fails with other special characters too but I have isolated the `\n` so far. – sscirrus Jul 19 '11 at 01:01
  • Is there an error reported in the console? – alex Jul 19 '11 at 01:05
  • @alex - unfortunately not. The `.js.erb` file simply doesn't do anything. If I test an identical file with no newline, it works. Nothing in the console. – sscirrus Jul 19 '11 at 01:06
  • I can't think of any reason why `\n` in a string would cause an issue when used like that. – alex Jul 19 '11 at 01:10
  • @alex, it's a basics of js -- see it's string vars. And as I understand there are not normal escaped "\n" there, but raw \n chars. – gaRex Jul 19 '11 at 01:16
  • Try double quotes around the erb substitution perhaps? – jaydel Jul 19 '11 at 01:16
  • @jaydel - no difference there. – sscirrus Jul 19 '11 at 01:17

2 Answers2

1

In PHP it could be as:

$("#body").val('<?=json_encode($letter->body)?>');

So find same json encode in ruby and you are done.

We need json encode as in js we can't have such var:

var f = 'daadsasd
asdadsdasdas';

only:

var f = 'daadsasd\nasdadsdasdas';

See:

Community
  • 1
  • 1
gaRex
  • 4,144
  • 25
  • 37
0

Rails 3.0:

$("#body").val(<%= @letter.body.to_json %>);

Rails 3.1:

$("#body").val(<%= j @letter.body %>);
Sam Ruby
  • 4,270
  • 22
  • 21