Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 872
Hans Avatar asked Jan 26 '26 20:01

Hans


2 Answers

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

like image 191
moff Avatar answered Jan 29 '26 09:01

moff


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);
like image 31
elon Avatar answered Jan 29 '26 10:01

elon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!