Reputation: 20882
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?
Upvotes: 20
Views: 36384
Reputation: 4865
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.
Upvotes: 10
Reputation: 17
A very simple solution.
var emoticon = ':)';
var val = $('#textarea').val();
$('#textarea').select().val(val + emoticon);
Upvotes: 0
Reputation: 16223
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);
});
Upvotes: 38
Reputation: 28355
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);
Upvotes: 0