简体   繁体   中英

append div to text area?

I've got a text area and I'm attempting to append a div to it. I'm trying to do it with Jquery like this...

var text = '<div class="item"><a class="as">q</a>test</div>';
$('#textArea').append(text);

The code runs without throwing any errors but my text doesn't appear inside the textarea. Why does this happen?

You cannot put div in textarea but sometimes you need to do so. Good news is that you can do it in other way by using contenteditable property of elements. Like

 <div contenteditable="true" style="min-height:50px; width:300px;" id="txtDiv">
 </div>

This Div will behave exactly like a Textarea but you can append anything you want. And remember when you want to grab data from inside it in jquery

 var ContentofDiv = $('#txtDiv').html();

Do you want to add it to the HTML structure or simply show the HTML Code as text ?
If you want to add it to the textarea HTML structure this will not work.
What you are searching for is
$('#textArea').text(text); or $('#textArea').text($('#textArea').text()+text);

.text() sets text of your textArea
.html() would set your html Content

You can't append to a textarea. Its text content behaves like other input.

var text = '<div class="item"><a class="as">q</a>test</div>';
$('#textArea').val( $('#textArea').val() + text);

尝试:

$('#textArea').val(text);

If you don't want to render the div's contents but simply want to display the HTML inside the textarea you need to convert the HTML first:

var lt='&lt;';
var gt='&gt;';
var text = '<div class="item"><a class="as">q</a>test</div>';
text = text.replace(/</gi, lt);
text = text.replace(/>/gi, gt);
$('#textArea').append(text);

And the HTML for the text area should look like this:

<textarea id="textArea"></textarea>

If you do want to render the div's contents inside the textarea use:

var text = '<div class="item"><a class="as">q</a>test</div>';
$('#textArea').append(text);

The HTML for the text area is the same as in the other example:

<textarea id="textArea"></textarea>

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