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.
- Click somewhere outside the text-box in order to blur the text-box.
- 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'?