开发者

How to copy newline characters from HTML div to textarea in jQuery?

开发者 https://www.devze.com 2023-03-24 21:58 出处:网络
Consider the following HTML page fragment: <div id=\'myDiv\'> Line 1.<br /> Line 2<br />

Consider the following HTML page fragment:

<div id='myDiv'>
    Line 1.<br />
    Line 2<br />
    These are &ltspecial&gt; characters &amp; must be escaped !@@&gt;&lt;&gt;
</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 &ltspecial&gt; characters &amp; must be escaped !@@&gt;&lt;&gt;
</pre></div>

And now .text() will return the text exactly as you specify it in the <pre> tag, even in IE.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号