I'm using the following HTML code to autoselect some text in a form field when a user clicks on the field:
<input onfocus="this.select()" type="text" value="Search">
This works fine in Firefox and Internet Explorer (the purpose being to use the default text to describe the field to the user, but highlight it so that on click they can just start typing), but I'm having trouble getting it to work in Chrome. When I click the form field in Chrome the text is highlighted for just a split second and then the cursor jumps to the end of the default text and the highlighting goes away.
Any ideas on how to get this working in Chrome as well?
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">
If you really insist on sticking with onfocus, then you'll need to add onmouseup="return false"
too.
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.
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.
The way I got around this was by creating a wrapper function that uses setTimeout()
to delay the actual call to select()
. Then I just call that function in the focus event of the textbox. Using setTimeout defers the execution until the call stack is empty again, which would be when the browser has finished processing all the events that happened when you clicked (mousedown, mouseup, click, focus, etc). It's a bit of a hack, but it works.
function selectTextboxContent(textbox)
{
setTimeout(function() { textbox.select(); }, 10);
}
Then you can do something like this to do the selection on focus:
<input onfocus="selectTextboxContent(this);" type="text" value="Search">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With