views:

481

answers:

3

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?

+1  A: 

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">
Bakhtiyor
That will handle the mouse, but not the keyboard. It would be much better to keep onfocus. I suspect the problem is something to do with the call to .select() rather than which event is being fired.
Dan M
@Dan, but tabbing into fields using the keyboard automatically selects their contents anyway.
Lee Kowalkowski
A: 

If you really insist on sticking with onfocus, then you'll need to add onmouseup="return false" too.

Lee Kowalkowski
A: 

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