简体   繁体   中英

Appending text from textarea to div on button click

I have a button that on a click event generates a div. The newly createded div is draggable and stays contained within another div. The issue: As the div is being created I am trying to append text to it. Nothing is getting appended due to not properly grabbing the value from the textarea and appending to the div. JSFIDDLE

Jquery

$('#button').click(function(e) {
    $('<div class="draggable" class="ui-widget-content"></div>').draggable({ containment: "parent" }).appendTo('.middle-side');
    $('textarea').val().appendTo('.draggable');
});

HTML

<textarea rows="4" cols="50" placeholder="Enter Text Here!"></textarea><br/>
 <input type="button" id="button" value="Add Div with Text"/><br/>

<div>
    <div class="middle-side"></div>
</div>

Use .text instead of .appendTo :

$('<div class="draggable" class="ui-widget-content"></div>')
    .draggable({ containment: "parent" })
    .appendTo('.middle-side')
    .text($('textarea').val())

Example: http://jsfiddle.net/0wbnud4k/11/

Alternatively, perhaps a little cleaner:

$('<div />', {
    'class': 'draggable ui-widget-content',
    text: $('textarea').val(),
    appendTo: '.middle-side',
    draggable: {
        containment: 'parent'
    }
});

Example: http://jsfiddle.net/0wbnud4k/13/

.appendTo is a method on the jQuery object. The text you retrieved with .val is just a string, and therefore does not have an .appendTo method.

You should use text method instead of appendTo and change it as follows:

var text = $('textarea').val();

$('.draggable').text(text);

you can also check it at:

http://jsfiddle.net/0wbnud4k/12/

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