How to append text to '<textarea>'?

2019-01-14 22:31发布

问题:

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?

回答1:

Try

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


回答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.



回答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>.



回答4:

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).



回答5:

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);