2

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!!

bagofmilk
  • 1,492
  • 8
  • 34
  • 69

3 Answers3

5

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.

Community
  • 1
  • 1
Kyle Muir
  • 3,875
  • 2
  • 22
  • 27
  • +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! – sgeddes Jul 14 '13 at 02:48
  • 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. – Kyle Muir Jul 14 '13 at 07:15
3

Try with this

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

DEMO

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
3

I would use .append() with createtextnode:

$('select').change(function() {
    $('#txtarea').append(document.createTextNode($(this).val()));   
})
sgeddes
  • 62,311
  • 6
  • 61
  • 83