I see that when I select text in a text field using the onfocus function, I do not get the expected behavior.
Here is a demo URL: http://jsfiddle.net/BquZz/
Below is a copy of the code:
<!DOCTYPE html> <html> <head> <title>Select all</title> <script type="text/javascript"> var text; var log; function select() { text.select(); log.innerHTML += ' - select'; } window.onload = function() { text = document.getElementById('text'); log = document.getElementById('log'); log.innerHTML = 'start'; text.onfocus = select; } </script> </head> <body> <input type="text" id="text" readonly="readonly" value="hello, world"> <div id="log"> </div> </body> </html>
I repeat the following experiment several times.
- Click anywhere outside the text box to blur the text box.
- Click on the text box to focus the text box.
I expect that each time at the end of step 2, you should select the line βhello worldβ in the text box. However, this is not what I am observing. Since Iceweasel 11.0 on Debian GNU / Linux (Wheezy), at the end of the alternative experiments "hello, world" is not selected. In the remaining experiments, sometimes I see that the string "hello, world" is fully selected, and sometimes partially selected. On Chrome 18.0.1025.33 beta on Debian GNU / Linux (Wheezy), I rarely get the desired result. In most cases, nothing is selected.
I know a way to fix this. Change text.onfocus = select to text.onclick = select . With the select() function called with onclick , I get the expected result. Here is a demo URL that shows the desired result using "onclick": http://jsfiddle.net/5EZwR/
Could you help me understand why I do not get the expected result with "onfocus", but I get it with "onclick"?
source share