开发者

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, 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜