The .val()
property of an item in jQuery for a <textarea>
doesn't seem to work with new lines. I need this function as the text-area is meant to recognize the enter key and display it as a preview, with the new line in tact.
However, what happens is shown in this fiddle: http://jsfiddle.net/GbjTy/1/. The text is displayed, but not in a new line.
How can I achieve the preview to include new lines, and I know it is possible, because it does this in the Stack Overflow Post Question preview.
Thanks.
P.S I have seen other links on SO relating to this, but they all say get the End User to use some code, which is not an ideal method for me. How can I achieve this without the End User writing any specific code, like here on SO Question Preview, where the Enter works as it should in the preview.
Your newlines output perfectly, but HTML ignores newlines: it needs
<br>
.Use a simple newline-to-br function like so:
jsfiddle here: http://jsfiddle.net/r5KPe/
Code from here: http://bytes.com/topic/javascript/answers/150396-replace-all-newlines-br-tags
I had tried to set the textarea value with jquery in laravel blade template, but the code was breaking because the variable had new lines in it.
my code snippet was
I solved my problem by changing my code snippet like below.
if any of you are facing this problem may take benifit from this.
You need to replace the new-line characters with
<br>
tags for HTML output.Here is a demo: http://jsfiddle.net/GbjTy/3/
The forced new lines in textareas are
\n
s, other HTML tags than textarea will ignore these. You have to use<br />
to force new lines at those elements.I suggest you use JavaScript to fix that rather than CSS as you already rely on JavaScript.
You can find the updated version here: http://jsfiddle.net/GbjTy/2/
I have found a more convenient method using jquery.
samplecode
HTML
JS
In the case that
you are NOT displaying the .val() of the textarea in another page (for example, submit form to Servlet and forward to another JSP).
using the .val() of the textarea as part of a URL encoding (e.g. a mailto: with body as textarea contents) within Javascript/JQuery
then, you need to URLEncode the textarea description as follows :