views:

130

answers:

2

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

A: 

This can be done using selection attributes:

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

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

Cory Larson