Reputation: 13217
I am focusing on an input field with jQuery:
$("input:text").focus();
There is already some text value in the input field. When I focus, the cursor blinks right after the last letter, how would I put the cursor right in front of the first letter?
Upvotes: 3
Views: 2124
Reputation: 1518
Add selectionStart to make it more crossbrowser
jQuery.fn.setCaret = function (pos) {
var input = this[0];
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(pos, pos);
} else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
} else if(input.selectionStart){
input.focus();
input.selectionStart = pos;
input.selectionEnd = pos;
}
};
// usage:
$('input:text').setCaret(0);
Upvotes: 1
Reputation: 6503
You could use this little plugin I created for you (modified from this script):
jQuery.fn.setCaret = function (pos) {
var input = this[0];
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(pos, pos);
} else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
};
// usage:
$('input:text').setCaret(0);
Demo: jsbin.com/iwetu3/2
Upvotes: 11