简体   繁体   中英

How to append text to '<textarea>'?

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?

Try

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

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.

您可以查看以下答案 ,该答案提供了一个很好的插件,用于在<textarea>中的插入位置插入文本。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM