0

I have a textarea that I am trying to fill with a list of words which have been fetched by a php script through AJAX, but when the list is diplayed in the textarea, the linebreaks are converted to (what appear to be) spaces (causing all the words to be on one line).

In the php I have tried:

echo implode("\n",$list); // and
echo implode("\r\n",$list); 

and none of these pass workable linebreaks to the javascript. I have searched this site (and others), and the general solution seems to be to replace any occurance of \n with \n\r. I tried that using javascript, more or less like so:

textarea.innerHTML = ajax_response.replace('/\n/g','\r\n');

however, this doesn't solve the problem. Is there something I'm missing? As I say, most solutions I've found online suggest to try the replacement, but is there any other workarounds for IE?

Thanks :)

hashi
  • 77
  • 9
  • http://stackoverflow.com/questions/5899202/line-breaks-wont-display-in-textarea-in-ie or http://stackoverflow.com/questions/5583040/show-newlines-in-html-textarea/5583094#5583094 – Mate Sep 24 '14 at 00:58
  • By default most Browsers take new lines and more than one white space and convert them to a single white space within HTML. – StackSlave Sep 24 '14 at 01:14

2 Answers2

1

set textarea.value instead of textarea.innerHTML

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • this worked. however I'm now having the same issue when I then try to take the value back from the textarea (after the user has edited it) and save it using ajax - however the linebreaks are remove here as well. – hashi Sep 24 '14 at 01:18
0

Try this:

echo implode('\\n', $list);

You want the backslash in the result, not a technological new line.

Additionally, a textarea is like an input. Use .value, instead of .innerHTML.

textareaElement.value = ajax_response;
StackSlave
  • 10,613
  • 2
  • 18
  • 35