20

http://jsfiddle.net/adamadam123/gEEVM/4/

I'm building a chat system that allows users to add emoticons.

Just like in the jsfiddler example above I take the current text in the textarea, combine it with the chosen emoticon symbol and then add this text back into the textarea.

$(function() {
    var data = $('textarea').val();
    var emoticon = ':)';
    $('textarea').val(data + emoticon);
    $('textarea').focus();
});  

The problem is when I set the focus back into the textarea the cursor is at the beginning of the text.

How can I set the cursor to the end of the text - to allow further typing?

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Adam
  • 19,932
  • 36
  • 124
  • 207

4 Answers4

38

Something simple you can do is reset the text area's value:

$(function() {
    var data = $('textarea').val();
    var emoticon = ':)';
    $('textarea').focus().val('').val(data + emoticon);
}); 
DarkAjax
  • 15,955
  • 11
  • 53
  • 65
  • With this you stress the DOM when it happen frequently, you clear the textarea and then add a bunch of data AGAIN with some extra's. That's not an add,not a polite way to add data. – Codebeat Jul 31 '18 at 23:30
10

First focus, then set value. Just like this JSFiddle

$('textarea').focus();
$('textarea').val("New Text");

Another way is to add this after .focus();

$('textarea').val($('textarea').val() + ' ');

It adds a space to the end of the textarea thus focuses at the end.

tozlu
  • 4,667
  • 3
  • 30
  • 44
1

A very simple solution.

var emoticon = ':)';
var val = $('#textarea').val();
$('#textarea').select().val(val + emoticon);
ADI
  • 19
  • 1
0

You should review this question:

jQuery Set Cursor Position in Text Area

Most elegant JQuery solution from there:

$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if (this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

With this, you can do

$('#elem').selectRange(3,5);
Community
  • 1
  • 1
VMAtm
  • 27,943
  • 17
  • 79
  • 125