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?
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.
Press f12 in the browser and check the element.
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).
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);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With