Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onclick vs. onfocus - Input text select behaviour differs. Why?

I see that when I select text in a text-box with the help of 'onfocus' function, I don't get the behaviour I expect.

Here is the demo URL: http://jsfiddle.net/BquZz/

A copy of the code follows:

<!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 multiple times.

  1. Click somewhere outside the text-box in order to blur the text-box.
  2. Click on the text-box in order to focus the text-box.

I expect that every time at the end of step 2, the string "hello, world" in the text-box should be selected. However, this is not what I observe. With Iceweasel 11.0 on Debian GNU/Linux (Wheezy), at the end of alternate experiments "hello, world" is not selected. In the remaining experiments, sometimes I see the string "hello, world" completely selected and sometimes, partially selected. With Chrome 18.0.1025.33 beta on Debian GNU/Linux (Wheezy), I rarely get the desired result. Most of the times, nothing is selected.

I know a way to fix this. Change text.onfocus = select to text.onclick = select. With the select() function invoked with onclick, I get the expected result. Here is a demo URL which shows the desired result using 'onclick': http://jsfiddle.net/5EZwR/

Could you please help me to understand why I do not get the expected result with 'onfocus' but I get it with 'onclick'?

like image 428
Susam Pal Avatar asked Mar 23 '12 12:03

Susam Pal


1 Answers

I think the problem is that .select() does two things: it sets the selection range to include all the text, and it causes the field to be focused. The browsers appear to dislike the repeated selection, though Chrome and Firefox behave differently.

If you change it to:

text.setSelectionRange(0, 10000);

then it works in Firefox. (I think it'd have to be different for Internet Explorer.)

edit — This Stackoverflow question has a good answer (Mr. Dimitrov's) that should work for all browsers.

like image 143
Pointy Avatar answered Oct 20 '22 00:10

Pointy