chrome setSelectionRange() not work in oninput handler

Viewed 17512

I'm working with some auto-completion code. setSelectionRange() is used to select text been completed in oninput event handler. It works at least in Firefox 14, but not in Chrome(6, 17).

Simplified code snippet demonstrating the problem is like this:

<input type='text' oninput='select()' />
function select(e){
    var s = this.value;
    if (s.length)
        this.setSelectionRange(s.length-1, s.length);
}

I debugged the code in chrome, and it turns out that text has been selected at first right after the setSelectionRange() been executed, but the selection disappeared later.

If i bind the handler to onclick instead of oninput, like this:

<input type='text' onclick='select()' />

then both browsers work fine.

Can anyone please give me some clue to make selection work in Chrome?

4 Answers

    
    
    var $input = document.getElementById('my_id');
    
    $input.onfocus = function () {
       $input.setSelectionRange(0, 7);
    }
    $input.focus();
    
    
<input type='text' id='my_id' value="My text for example." />

On Angular for example you can do this:

@ViewChild('input', { static: false }) inputElement: ElementRef;

focus(){    
    setTimeout(() => {
        this.inputElement.nativeElement.focus();
        this.inputElement.nativeElement.setSelectionRange(this.valueInput.length, this.valueInput.length);
    });
}

I think setTimeout does not the best solution. You just need call event handler before use setSelectionRange. i use this:

e.currentTarget.value = previousValue;
onChange(e);
e.currentTarget.setSelectionRange(startPosition, endPosition);
Related