Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQUERY Set Textarea Cursor to End of Text

Tags:

html

jquery

css

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?

like image 701
Adam Avatar asked Nov 16 '12 22:11

Adam


People also ask

How do I change the cursor position in textarea?

To set the cursor at the end of a textarea: Use the setSelectionRange() method to set the current text selection position to the end of the textarea. Call the focus() method on the textarea element. The focus method will move the cursor to the end of the element's value.

How do I change cursor position to the top left edge of input?

Press f12 in the browser and check the element.

How can get current cursor position in textbox using jQuery?

For exactly what you're after, there's the jQuery Caret (jCaret) plugin. For your code to get the position you could do something like this: $("#myTextInput"). bind("keydown keypress mousemove", function() { alert("Current position: " + $(this).


2 Answers

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);
}); 
like image 92
DarkAjax Avatar answered Oct 02 '22 13:10

DarkAjax


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.

like image 30
tozlu Avatar answered Oct 02 '22 13:10

tozlu