Hi, I have a text area in which user enters text. I want to retrieve the text as user entered including the new line character which is automatically wrapped. how to get textarea's text using jQuery with newline character preserved?
you need to replace the "\n" with br tags or wrap the content in pre to see the nextlines.
Here's a sample code:
assuming you have your page markup like this:
<div id="res"></div>
<textarea id="txtarea"></textarea>
<button id="btn">go</button>
then this is the jquery code:
$(document).ready(function() {
var btn = $('#btn');
var txtarea = $('#txtarea');
var result = $('#res');
btn.click(function() {
var val = txtarea.val().replace(/\n/g, '<br/>');
result.html(val);
return false;
});
});
I hope this helps.
I want to keep automatically wrapped newlines.
You just cannot do that, because there are no newline characters there. Textarea control is doing the visual wrapping for you. There is no new lines, unless you type them in.
Given your edit, its going to be pretty hard, if not impossible to do it accurately. The problem is that automatic wrapping doesn't actually insert any newline characters, it's just the browser rendering the one string across multiple lines... So the only way I can think of is to try & write some code to estimate where the newlines were rendered based on the width of the textarea
and manually insert them.
So with that in mind if your text area doesn't have a CSS width set and you use the cols="xx"
attribute and you use a fixed width font and you always have the scrollbars showing (this effects how wide the textarea is rendered based of cols
), then you should be able calculate the number of words displayed on a single line before it gets automatically wrapped by the browser by doing something like this:
//Based off <textarea id="text" cols="50" rows="5" style="overflow: scroll">This is a test sentence, with no newline characters in it, but with an automatically wrapped sentence that spans three lines.</textarea>
var words = $("#text").val().split(" ");
var cols = $("#text").attr("cols");
var text = "";
var lineLength = 0;
for (var i = 0; i < words.length; i++) {
var word = words[i];
if ((lineLength + word.length + 1) > cols) {
text += "\n";
lineLength = 0;
} else if (lineLength > 0) {
text += " ";
lineLength++;
}
text += word;
lineLength += word.length;
}
alert(text);
//Alerts:
//This is a test sentence, with no newline
//characters in it, but with an automatically
//wrapped sentence that spans three lines.
However, that's a lot of ifs, and I don't know how well this would work across all browsers (I tested it & it appears to work in Firefox 3.6)...
Also note if you do go down this route, that my word wrapping code is very rudimentary and is virtually guaranteed not to match what the browser is doing in all cases, so you may need to expand on it depending on what your exact requirements are. For example, words longer than the cols
length get split by firefox, but not by my code.