开发者

Cursor location in text-input fields

开发者 https://www.devze.com 2022-12-12 06:59 出处:网络
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.

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, act开发者_开发技巧ually, 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...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号