jQuery append HTML code into textarea

17,310

Solution 1

Try with this

$(document).ready(function() {
    $('select').change(function() {
        var currentVal = $('textarea').val();
        $('textarea').val(currentVal + $(this).val());    
    });
});

DEMO

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()));   
})
Share:
17,310
bagofmilk
Author by

bagofmilk

I am a bag of milk

Updated on June 04, 2022

Comments

  • bagofmilk
    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>&#60;&#62;&#60;&#47;&#62;</option>
      <option>&#60;p&#62;&#60;&#47;p&#62;</option>
      <option>&#60;div&#62;&#60;&#47;p&#62;</option>
      <option>&#60;a&#62;&#60;&#47;a&#62;</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
    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
    Kyle Muir almost 11 years
    Thanks 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.