Skip to content Skip to sidebar Skip to footer

Problem With Chrome Form Handling: Input Onfocus="this.select()"

I'm using the following HTML code to autoselect some text in a form field when a user clicks on the field: This

Solution 1:

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

Solution 2:

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


Solution 3:

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.


Solution 4:

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.


Solution 5:

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

Post a Comment for "Problem With Chrome Form Handling: Input Onfocus="this.select()""