Onclick vs. onfocus - The text input behavior is different. What for?

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"?

+4
source share
1 answer

I think the problem is that .select() does two : it sets a selection range that includes all the text and that causes the field to focus. Browsers do not seem to like reselection, although Chrome and Firefox behave differently.

If you change it to:

 text.setSelectionRange(0, 10000); 

then it works in firefox. (I think it should be different for Internet Explorer.)

edit - This question in Stackoverflow has a good answer (Mr. Dimitrov), which should work for all browsers.

+1
source

Source: https://habr.com/ru/post/1403069/


All Articles