Destrictor
Destrictor

Reputation: 752

Select all contents of textbox when it receives focus

I saw the script at Select all contents of textbox when it receives focus (JavaScript or jQuery).

Unfortunately, when trying to implement it for IE10, I came to the conclusion that the focus gets cleared at a later time as well, and preventing default (which worked for WebKit-based browsers) simply didn't seem to work.

I managed to make it function correctly in IE10, but it feels a bit dirty with the extra boolean var.

(basic) html:

<div id="ContentDiv">
    <input type="text" value="default" />
</div>

code:

$(document).ready(initialize);

function initialize() {
    var tmp;
    $("#ContentDiv").on({
        focus: function (e) {
            //select for all browsers
            $(this).select();
            tmp = true;
        },
        mouseup: function (e) {
            //reselect for IE10
            if (tmp) {
                this.select();
                tmp = false;
            }
            //chrome still needs this
            e.preventDefault();
        }
    }, "input:text");
}

example: jsfiddle

My question: Does anyone know of a cleaner way around this select-on-focus issue?

Upvotes: 1

Views: 2081

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

So, using a timeout only:

http://jsfiddle.net/2BjQv/

$(document).ready(initialize);

function initialize() {
    $("#ContentDiv").on({
        focus: function (e) {
            setTimeout(function(){e.target.select();},0);
        }
    }, "input:text");
}

Seems a little buggy in firefox.

Upvotes: 2

Related Questions