Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

jquery - The .val() of a textarea doesn't take new lines into account

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's a CSS problem, not a JavaScript problem. HTML collapses white space by default — this includes ignoring newlines.

Add white-space: pre-wrap to the output div. http://jsfiddle.net/mattball/5wdzH/

This is supported in all modern browsers: https://caniuse.com/#feat=css3-tabsize


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...