How to append text to '<textarea>'?

2019-01-14 22:30发布

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?

5条回答
疯言疯语
2楼-- · 2019-01-14 22:57

Try

var myTextArea = $('#myTextarea');
myTextArea.val(myTextArea.val() + '\nYour appended stuff');
查看更多
我命由我不由天
3楼-- · 2019-01-14 22:57

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

查看更多
地球回转人心会变
4楼-- · 2019-01-14 23:04

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

查看更多
劫难
5楼-- · 2019-01-14 23:08

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.

查看更多
该账号已被封号
6楼-- · 2019-01-14 23:18

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);
查看更多
登录 后发表回答