views:

73

answers:

2

Hi,

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?

+6  A: 

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

moff
+1 but could you explain that a bit?
D_N
@D_N: It first checks if input.setSelectionRange, the object which every browser except IE uses, is available. If it is, it focuses the field and positions the caret at the specified position. If it isn't available, it checks for the IE method and uses that instead.
moff
Aha, wondered if it was a browser thing. Thanks.
D_N
A: 

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);
elon