jQuery append HTML code into textarea
Solution 1
Try with this
$(document).ready(function() {
$('select').change(function() {
var currentVal = $('textarea').val();
$('textarea').val(currentVal + $(this).val());
});
});
Solution 2
Create a temporary variable outside your event handler and keep appending to that, then update the textarea with the variable value, like this:
var tempValue = '';
http://jsfiddle.net/KyleMuir/vWFQQ/1/
The issue you're going to run in to is that change()
will not pick up the multiple selections for the same drop down, however, this solution here: https://stackoverflow.com/a/898761/2469255 may be of use...
Hope this helps
EDIT: see this updated fiddle for the .selected()
extension.
Solution 3
I would use .append() with createtextnode
:
$('select').change(function() {
$('#txtarea').append(document.createTextNode($(this).val()));
})
Comments
-
bagofmilk almost 2 years
I'm trying to 'append' HTML elements into a textarea. I figured out how to insert the HTML elements:
see here -------> jsFiddle <--------
But I cannot figure out how to APPEND.
Here's the code anyways:
HTML
<select id='sel' size='1'> <option><></></option> <option><p></p></option> <option><div></p></option> <option><a></a></option> </select><br/><br/> <textarea id='txtarea'></textarea>
jQuery
$(document).ready(function() { $('select').change(function() { $('textarea').html($(this).val()); }); });
Does anyone know how to APPEND html element text to the textarea? What I mean is if you keep clicking the "<p></p>" item it will keep inserting itself after the other.
Thanks!!
-
sgeddes almost 11 years+1 -- great explanation. Didn't think about that with the
change()
event (although makes sense). I still prefer the.append()
method, but this is the best solution! -
Kyle Muir almost 11 yearsThanks for the comment, I don't know why but I personally dislike mixing vanilla JS and jQuery. I don't have a compelling reason for it, it just feels wrong to me.