Monday, May 20, 2024
176
rated 0 times [  178] [ 2]  / answers: 1 / hits: 19023  / 12 Years ago, mon, july 30, 2012, 12:00:00

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?


More From » google-chrome

 Answers
17

There are some problems with your code, namely that the parameters passed into the select() function are wrong: this will be window and e will be undefined. Also, using select() as a function name within the oninput attributes causes a problem because select will resolve to the select() method of the input itself. A better approach is usually to set the event handler in script rather than via an event handler attribute.



However, the problem exists even after correcting these issues. Possibly the input event fires before the browser has moved the caret in Chrome. A simple workaround would be to use a timer, although this is sub-optimal because there's a possibility the user will be able to input another character before the timer fires.



Demo: http://jsfiddle.net/XXx5r/2/



Code:



<input type=text oninput=selectText(this)>

<script type=text/javascript>
function selectText(input) {
var s = input.value;
if (s.length) {
window.setTimeout(function() {
input.setSelectionRange(s.length-1, s.length);
}, 0);
}
}
</script>

[#83982] Saturday, July 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominickmackenziet

Total Points: 583
Total Questions: 101
Total Answers: 117

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
dominickmackenziet questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Fri, Feb 12, 21, 00:00, 3 Years ago
;