I am trying to copy (with jQuery and JS) text written in a textarea to a pre tag. However, I cannot introduce as many line breaks as I want. For instance, if I press Enter once, it works and I create a line break, but if I press Enter more than once I cannot get more than one line break. Do you know why this happens, or how I can fix it?
The code goes pretty much like this:
<textarea id="area" rows="5" cols="30"> </textarea>
<pre id="area2" >开发者_如何学编程 </pre> <br/>
<script>
newText = $( '#area' ).val();
$( '#pre' ).text( newText);
</script>`
The id of the textarea is #area and the id of the pre tag is #pre
I had this problem with IE7. It doesn't display more that one newline within a pre tag.
Have you tried doing
$( '#pre' ).html( newText);
instead? It could be that the .text
strips out the \n
's
If this doesn't work, I've found some answer to a similar questions here on Stack Overflow, which might work for you. However it's kind of a pain since you've got to write a rather big function that detects the newlines and replaces them:
//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;
}
$( '#pre' ).text(text);
//Alerts:
//This is a test sentence, with no newline
//characters in it, but with an automatically
//wrapped sentence that spans three lines.
精彩评论