简体   繁体   中英

Cursor location in text-input fields

There is a lot of information on how to place the cursor exactly where you want it to be in a textarea. None of it seems to work for an <input type="text"> field.

Basically, when the page loads, I have an input field with text in it, and it's focused. The problem is that the cursor is at the end of the pre-written text. I need it to be at the beginning. Alternatively, hiding the the cursor would be fine, too. Even better, actually, but I don't know if this is possible.

Ideally this would be done in jQuery, but regular JS is fine too.

Thanks!
Mala

This can be done using selection attributes:

$('#my-element-id').attr({
    selectionStart : 0,
    selectionEnd   : 0
});

Not sure what jQuery does under the hood for Jordan's answer, but this one might be a little more cross-browser:

function setSelectionRange(inputEl, selStart, selEnd) { 
    if (inputEl.setSelectionRange) { 
        inputEl.focus(); 
        inputEl.setSelectionRange(selStart, selEnd); 
    } else if (inputEl.createTextRange) { 
        var range = inputEl.createTextRange(); 
        range.collapse(true); 
        range.moveEnd('character', selEnd); 
        range.moveStart('character', selStart); 
        range.select(); 
    } 
}

And if you're coupling it with jQuery, use it like:

$(document).ready(function() {
    $('input[type="text"]').each(function() {
        setSelectionRange(this, 0, 0);
    });
});

BTW, this code is completely untested.

EDIT: Updated code after I saw you were looking for input elements...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM