Chrome setSelectionRange () not working in oninput handler

I work with an auto-delivery code. setSelectionRange() used to select the text completed in the oninput event oninput . It works at least in Firefox 14, but not in Chrome (6, 17).

A simplified code snippet showing the problem is as follows:

 <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 turned out that the text was selected first immediately after running setSelectionRange() , but the selection disappeared later.

If I bind the handler to onclick instead of oninput , for example:

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

then both browsers work fine.

Can someone please give me some tips to do a select job in Chrome?

+8
source share
2 answers

There are some problems with your code, namely that the parameters passed to the select() function are incorrect: this will be window , and e will be undefined. Also, using select() as the function name in the oninput attributes causes a problem, because select will solve the select() method of the input itself. The best approach, as a rule, is to set the event handler in the script, and not through the attribute of the event handler.

However, the problem exists even after resolving these problems. Perhaps 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 not optimal, because there is a possibility that the user will be able to enter another character before the timer fires.

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

the 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> 
+13
source

 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." /> 
0
source

All Articles