Cursor moves to the beginning of a text field

I have a certain problem with IE8 (and only IE), when I focus an input field which has text in it the cursor moves to the beginning of that field. I'm trying to set the cursor at the end. I've googled around and found the following solution:

function setSelectionRange(input, selectionStart, selectionEnd) {
    input = document.getElementsByTagName("input")[0];
    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

"Input" here is simply an input field which is in a class (var inputElement = this.input;). The problem is that both "setSelectionRange" and "createTextRange". Am I doing something wrong? Is createTextRange defined only for TextArea?

@Edit: well it appears I was using something like "two objects" a js input and a jquery input, after changing input to document.getElementsByTagName("input")[0]; I am able to go to "createTextRange" branch but it still doesn't change the position of the cursor.

@Edit2: I changed the code a bit, now I'm getting the input from the document and it enters the if branch. But then the browser shows me:

Unexpected call to method or property access.

On this line var range = input.createTextRange();

@Edit3: To answer James' question. I have a class and in that class, the whole thing is associated with a jsp which has an input. In this class I set a focus handler for the field which is associated with the input form the jsp inputElement.focus(onInputFocus) then I have something like this:

function onInputFocus() {
    isFocused = true;
    valueDivElement.hide();
    labelElement.html(labelFocus);
    if (currentData.selectedEntityCode) {
        inputElement.val(currentData.selectedEntityCode);
        inputElement.attr('title', currentData.selectedEntityCode);
    } else {

    }

    var input = document.getElementsByTagName("input")[0];
    input.value = input.value;
}

The whole class is obviously much larger and this is not my code but I'm guessing this is the last thing that's being executed.

6
задан Mateusz Dymczyk 23 November 2010 в 15:15
поделиться