Alex Rivera | Logout

problem with Chrome form handling: input onfocus="this.select()"

Asked 2010-05-30T14:59:33.560
25

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?

Edit
Report

3 Answers

17

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

answered 2010-06-04T10:13:56.553
3

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.

answered 2012-07-20T19:42:21.053
2

Just use <input onmouseup=select()>. That works in all browsers.

answered 2012-12-21T02:42:16.727

Your Answer