Björn
Björn

Reputation: 13217

Focus on input field with value

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

Answers (2)

elon
elon

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

moff
moff

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

Related Questions