Add text to textarea - Jquery

115,433

Solution 1

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

Solution 2

That should work. Better if you pass a function to val:

$('#replyBox').val(function(i, text) {
    return text + quote;
});

This way you avoid searching the element and calling val twice.

Share:
115,433
Oliver 'Oli' Jensen
Author by

Oliver 'Oli' Jensen

Learning PHP - Beginner

Updated on July 22, 2022

Comments

  • Oliver 'Oli' Jensen
    Oliver 'Oli' Jensen almost 2 years

    How can I add text from a DIV to a textarea?

    I have this now:

        $('.oquote').click(function() { 
          $('#replyBox').slideDown('slow', function() {
          var quote = $('.container').text();   
             $('#replyBox').val($('#replyBox').val()+quote);   
            // Animation complete.
          });    
        });
    
  • Felix Kling
    Felix Kling almost 13 years
    @AlienWebguy: Better than $('#replyBox').val($('#replyBox').val()+quote); because it does not search the element and call val twice.
  • Oliver 'Oli' Jensen
    Oliver 'Oli' Jensen almost 13 years
    This doesn't add the text in the textarea, but outside of it.
  • AlienWebguy
    AlienWebguy almost 13 years
    No it doesn't :) Look at the code and inspect the element. You might be thinking of after()
  • Oliver 'Oli' Jensen
    Oliver 'Oli' Jensen almost 13 years
    Although: It add the text, but it creates many spaces. How can this be avoided?
  • Oliver 'Oli' Jensen
    Oliver 'Oli' Jensen almost 13 years
    Hmm. Not that good with jQuery. I tried this: $('#texta').append($(jQuery.trim('#reply<?php echo $forumPost['post_id']; ?>')).text()) But it did not work.
  • AlienWebguy
    AlienWebguy almost 13 years
    What are the values of both nodes before one is appended to the other?
  • viktor_vangel
    viktor_vangel almost 8 years
    Use .val() not .append() or you'll face issues.
  • Jpsy
    Jpsy about 7 years
    @ermenkoff is very right. I had cases where .append() worked and others where it was simply ignored for no obvious reason. The answer of Felix Kling using .val() is stable and should be preferred!
  • Marco Torchiano
    Marco Torchiano about 7 years
    append() only works if you did not change the content of the textarea befor (e.g. by typing)!!
  • Nathan Do
    Nathan Do about 7 years
    It won't work when the textarea is already edited. stackoverflow.com/questions/4722914/…
  • brandito
    brandito over 4 years
    I had to use .text() instead of .val() otherwise it just kept appending even though I had reset the contents completely.