简体   繁体   中英

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 &ltspecial&gt; characters &amp; must be escaped !@@&gt;&lt;&gt;
</div>
<input type='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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM