How to copy newline characters from HTML div to textarea in jQuery?
Consider the following HTML page fragment:
<div id='myDiv'>
Line 1.<br />
Line 2<br />
These are <special> characters & must be escaped !@@><>
</div>
<input type=开发者_StackOverflow'button' value='click' id='myButton' />
<textarea id='myTextArea'></textarea>
<script>
$(document).ready(function () {
$('#myButton').click(function () {
var text = $('#myDiv').text();
$('#myTextArea').val(text);
});
});
</script>
First, there is a div element with id myDiv
. It contains some text similar to what might be retrieved form a SQL database at runtime in my production web site.
Next, there is a button and a textarea. I want the text in myDiv
to appear in the textarea when the button is clicked.
However, using the code I provided, the line-breaks are stripped out. What can I do about this, taking into consideration that escaping special characters is absolutely non-negotiable?
Your code works great for me in both Firefox and Chrome: http://jsfiddle.net/jYjRc/
However, if you have a client that doesn't do what you want, replace <br>
s with newline characters.
Edit: Tested in IE7 and the code breaks. So I updated the fiddle with my suggestion: http://jsfiddle.net/jYjRc/1/
Do your HTML like so:
<div id='myDiv'><pre>
Line 1.
Line 2
These are <special> characters & must be escaped !@@><>
</pre></div>
And now .text()
will return the text exactly as you specify it in the <pre>
tag, even in IE.
精彩评论