ApplePie
ApplePie

Reputation: 1185

Input in textarea does not display as typed in

I have an inputarea for user to type some text. However, when the text gets updated it does not shows as the user has type in. For example, the new lines are not showing up.

Here is what the user typed in:

enter image description here

And here is how it shows up after update (Everything goes into one line.):

enter image description here

Can someone please advise how to fix this?

Upvotes: 1

Views: 59

Answers (1)

Michael Coker
Michael Coker

Reputation: 53709

You're going to need to convert the new lines to br's or you can put the text in a pre element (or an element with white-space: pre* CSS).

$('textarea').on('keyup',function() {
  var text = $(this).val();
  $('pre').html(text);
  $('article').html(text);
  $('div').html(text.replace(/(?:\r\n|\r|\n)/g, '<br />'))
})
* {margin:0;padding:0;}
pre {
  border: 1px solid blue;
}
div {
  border: 1px solid red;
}
article {
  border: 1px solid green;
  white-space: pre-line;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>

<pre></pre>

<div></div>

<article></article>

Upvotes: 2

Related Questions