Focus on input field with value

I focus on the input field using jQuery:

$("input:text").focus();

The input field already has a text value. When I focus, the cursor blinks immediately after the last letter, how would I place the cursor right before the first letter?

+3
source share
2 answers

You can use this little plugin that I created for you (modified 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

+11
source

Add selectionStart to make it more complex.

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);
+1
source

Source: https://habr.com/ru/post/1736886/


All Articles