1

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?

Community
  • 1
  • 1
Destrictor
  • 752
  • 1
  • 4
  • 15
  • Check this : http://stackoverflow.com/questions/5797539/jquery-select-all-text-from-a-textarea – Arpit May 30 '13 at 13:25
  • @Arpit The pure javascript version seems to work, unfortunately once a bit of jquery is thrown in the mix, it doesn't seem to work. See http://jsfiddle.net/nrWep/3/ and http://jsfiddle.net/nrWep/4/ . – Destrictor May 30 '13 at 13:41

1 Answers1

2

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.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • It works quite well, though I think if you use a timeout, you don't even need to trigger a custom event (see [jsfiddle](http://jsfiddle.net/2BjQv/1/)). I'd think the myFocus event gets processed immediately and the control returns to the focus event. Correct me if I'm wrong. On the other hand, I'd rather not use setTimeout, because this might be a cause for issues on slower computers. – Destrictor May 30 '13 at 13:48
  • You are correct, no need of custom event if using timeout. But i cannot think of another way without using a timeout. BTW, seems a bit buggy in FF. – A. Wolff May 30 '13 at 13:54
  • Well I'm gonna leave this open for a bit more. If no one else finds a nice way without the extra bool or the setTimeout, I'll give you the answer, because this is a __lot__ more concise than the current popular method of fixing the select in chrome :). – Destrictor May 30 '13 at 14:00