How to append text to '<textarea>'?

39,186

Solution 1

Try

var myTextArea = $('#myTextarea');
myTextArea.val(myTextArea.val() + '\nYour appended stuff');

Solution 2

This took me a while, but the following jQuery will do exactly what you want -- it not only appends text, but also keeps the cursor in the exact same spot by storing it and then resetting it:

var selectionStart = $('#your_textarea')[0].selectionStart;
var selectionEnd = $('#your_textarea')[0].selectionEnd;

$('#your_textarea').val($('#your_textarea').val() + 'The text you want to append');

$('#your_textarea')[0].selectionStart = selectionStart;
$('#your_textarea')[0].selectionEnd = selectionEnd;

You should probably wrap this in a function though.

Solution 3

You may take a look at the following answer which presents a nice plugin for inserting text at the caret position in a <textarea>.

Solution 4

You could use my Rangy inputs jQuery plugin for this, which works in all major browsers.

var $textarea = $("your_textarea_id");
var sel = $textarea.getSelection();
$textarea.insertText("\nSome text", sel.end).setSelection(sel.start, sel.end);

Solution 5

You can use any of the available caret plugins for jQuery and basically:

  1. Store the current caret position
  2. Append the text to the textarea
  3. Use the plugin to replace the caret position

If you want an "append" function in jQuery, one is easy enough to make:

(function($){
    $.fn.extend({
        valAppend: function(text){
            return this.each(function(i,e){
                var $e = $(e);
                $e.val($e.val() + text);
            });
        }
    });
})(jQuery);

Then you can use it by making a call to .valAppend(), referencing the input field(s).

Share:
39,186
daGrevis
Author by

daGrevis

Hacker working with Clojure, Python, ReactJS and Docker. Enjoys r/unixporn and r/vim. Loves DotA 2, blues rock and gym. Really loves his girlfriend. https://twitter.com/daGrevis https://github.com/daGrevis https://news.ycombinator.com/user?id=daGrevis https://lobste.rs/u/daGrevis http://www.linkedin.com/in/daGrevis

Updated on June 27, 2020

Comments

  • daGrevis
    daGrevis almost 4 years

    I have <textarea> where user can type in his message to the world! Below, there are upload buttons... I would love to add link to uploaded file (don't worry, I have it); right next to the text that he was typing in.

    Like, he types in 'Hello, world!', then uploads the file (its done via AJAX), and the link to that file is added in next line to the content of <textarea>. Attention! Is it possible to keep cursor (place where he left to type) in the same place?

    All that may be done with jQuery... Any ideas? I know that there are method 'append()', but it won't be for this situation, right?

  • daGrevis
    daGrevis almost 13 years
    Without making the caret to stay in the same position... how to do it? I'm simply searching for something like append() to <textarea>. val() maybe?
  • Brad Christie
    Brad Christie almost 13 years
    @deGrevis: In addition to @Darin's post, you can also use this function from another answer to insert it at the caret position.
  • Pointy
    Pointy almost 13 years
    @daGrevis the value of a textarea is just a string; you don't need any special "append()" function.
  • Brad Christie
    Brad Christie almost 13 years
    @deGrevis: or var $ta = $('textarea'); $ta.val($ta.val() + 'new text');
  • daGrevis
    daGrevis almost 13 years
    Looks awesome! What element did you meant with #a?
  • fletom
    fletom almost 13 years
    @daGrevis Oops! I meant that to say #your_textarea, it was just called #a when I was testing.
  • Tim Down
    Tim Down almost 13 years
    selectionStart and selectionEnd aren't supported in IE < 9.
  • daGrevis
    daGrevis almost 13 years
    Really awesome (that you didn't use any other, extra plugins), but bad that it doesn't support IE 9 <. That's why I can't accept... sorry.
  • fletom
    fletom almost 13 years
    @daGrevis If I were you, I would use this and ask users to update their browser to be fully supported. The interface wouldn't even be completely broken, they just wouldn't have their selection preserved. It's sort of like giving IE 6 users square corners instead of CSS 3 rounding.
  • fletom
    fletom almost 13 years
    @daGrevis I just think writing code the right way instead of using all kinds of hacks and workarounds to support outdates software is more important than having everything work the same on every browser. You get the advantages of better, more robust, easier to write code -- and not only for this case, but for any future code you write. Things also would be faster because you aren't loading all these plugins, etc.
  • daGrevis
    daGrevis almost 13 years
    I do totally agree to you, man. Only problem - my boss do not.
  • fletom
    fletom almost 13 years
    @daGrevis Ah, in that case I sympathize with you. There are a lot of articles online about how it's okay for things to work a bit differently in ancient browsers, so maybe you could send one to your boss and see what happens. Anyways, good luck.
  • Tim Down
    Tim Down almost 13 years
    @nomulous: I totally disagree. First, IE 9 has been out for 4 months, so expecting everyone to have upgraded already is unrealistic. Second, IE 9 is not available for Windows XP, so huge numbers of people will be simply unable to upgrade for several years to come. Third, and most important, typical users don't care one little bit what the developer had to do to make the page they're looking at work in their browser, and nor should they. You serve your users, not the other way round. Writing code "the right way" on the web means using workarounds and is necessarily a dirty business.
  • fletom
    fletom almost 13 years
    @Tim Down It takes almost no effort at all to upgrade to the latest and greatest browser version, and users have every reason to. I have no sympathy for people that are using an operating system almost a decade out of date. Windows XP was released when Apple was still shipping Mac OS 9 on their computers. There have been two major Windows releases since then. If you were using hardware from ten years ago, you wouldn't expect the latest games, etc. to run on it. The same should go for people who use out of date software.
  • Tim Down
    Tim Down almost 13 years
    @nomulous: You're making the mistake of thinking that every user is like you. A large percentage of users just press the big blue "e" for the internet and don't know what a web browser is and don't care. Many others are on corporate networks and have no control over the software on their PCs. For IT departments, upgrading browser's company-wide is often an enormous deal. As a web developer, you need to understand that you're in a small minority of users who are able and know and care enough about browsers to upgrade regularly. Lastly, if Vista had been better there would be fewer XP users now.
  • fletom
    fletom almost 13 years
    @Tim Down The fact that users just press the internet explorer icon is irrelevant. If you tell them that they need to upgrade their browser for things to work properly, they will. And lots of sites are already doing this! People don't necessarily find it easy upgrading hardware either, but when their computers are running slowly and not working, they sure do it. The same goes for browsers and operating systems. If you just let users use whatever is on their computers even if it was made ten years ago, you're part of the problem.
  • Uday Hiwarale
    Uday Hiwarale over 10 years
    But wouldn't it increase time as your text goes increasing?
  • Johann
    Johann over 7 years
    So you search the DOM twice to find yourTextarea? Not good. Search once and store it as a variable.
  • Alex P.
    Alex P. almost 5 years
    It's not jQuery, you are using it just to find the element. The code actually would be simpler without it :) (or just assign $('selector')[0] to a variable)