How can I get the caret position from within an input field?
I have found a few bits and pieces via Google, but nothing bullet proof.
Basically something lik
There are a few good answers posted here, but I think you can simplify your code and skip the check for inputElement.selectionStart
support: it is not supported only on IE8 and earlier (see documentation) which represents less than 1% of the current browser usage.
var input = document.getElementById('myinput'); // or $('#myinput')[0]
var caretPos = input.selectionStart;
// and if you want to know if there is a selection or not inside your input:
if (input.selectionStart != input.selectionEnd)
{
var selectionValue =
input.value.substring(input.selectionStart, input.selectionEnd);
}
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if (document.selection) {
// IE
input.focus();
}
return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
}
})(jQuery);
There is now a nice plugin for this: The Caret Plugin
Then you can get the position using $("#myTextBox").caret()
or set it via $("#myTextBox").caret(position)