How do you set the cursor position in a text field using jQuery? I\'ve got a text field with content, and I want the users cursor to be positioned at a certain offset when
As for me here the most easily way to add text(Tab -> \t) in textarea by cursor position and save the focus on cursor:
$('#text').keyup(function () {
var cursor = $('#text').prop('selectionStart');
//if cursot is first in textarea
if (cursor == 0) {
//i will add tab in line
$('#text').val('\t' + $('#text').val());
//here we set the cursor position
$('#text').prop('selectionEnd', 1);
} else {
var value = $('#text').val();
//save the value before cursor current position
var valToCur = value.substring(0, cursor);
//save the value after cursor current position
var valAfter = value.substring(cursor, value.length);
//save the new value with added tab in text
$('#text').val(valToCur + '\t' + valAfter);
//set focus of cursot after insert text (1 = because I add only one symbol)
$('#text').prop('selectionEnd', cursor + 1);
}
});