I\'m using the following HTML code to autoselect some text in a form field when a user clicks on the field:
Instead of binding to onfocus event you must bind this action into onclick event and it will work as you wanted.
<input onclick="this.select()" id="txt1" name="txt1" type="text" value="Search">
This works best for me...
<input type="text" onfocus="this.searchfocus = true;" onmouseup="if(this.searchfocus) {this.select(); this.searchfocus = false;}" />
The mouseup event fires after onfocus.
onfocus="setTimeout(function(){select(this)})"
or onfocus="setTimeout(function(){select(this)},118)"
for Firefox.
Just use <input onmouseup=select()>
. That works in all browsers.
Building on Jason's answer, here is a function that replaces the "select" function of DOM input nodes with an updated version that has the timeout built in:
if (/chrome/i.test(navigator.userAgent)) {
HTMLInputElement.prototype.brokenSelectFunction =
HTMLInputElement.prototype.select;
HTMLInputElement.prototype.select = function() {
setTimeout(function(closureThis) { return function() {
closureThis.brokenSelectFunction();
}; }(this), 10);
};
}
Basically, (in Chrome only) we just renamed the built-in but broken select() function to brokenSelectFunction() and then added a new function to all inputs called select() that calls brokenSelectFunction() after a delay. Now, just call select() normally, as the built-in select function has been replaced by the fixed function with Jason's delay suggestion.
This way, you don't have to worry about changing your existing calls to use a wrapper function (and once this is resolved in Chrome, you can just remove the above shim and go back to normal).
textbox.select(); // now runs select with setTimeout built-in (in Chrome only)
Edit: you might want to change the user-agent match from "chrome" to "webkit", as this issue happens in all webkit-browsers including Safari, and this fix will work for any of them.
This is a solution working in Firefox, Chrome and IE, both with keyboard focus and mouse focus. It also handles correctly clicks following the focus (it moves the caret and doesn't reselect the text):
<input
onmousedown="this.clicked = 1;"
onfocus="if (!this.clicked) this.select(); else this.clicked = 2;"
onclick="if (this.clicked == 2) this.select(); this.clicked = 0;"
>
With keyboard focus, only onfocus
triggers which selects the text because this.clicked
is not set. With mouse focus, onmousedown
triggers, then onfocus
and then onclick
which selects the text in onclick
but not in onfocus
(Chrome requires this).
Mouse clicks when the field is already focused don't trigger onfocus
which results in not selecting anything.