Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: cross browser solution for selecting all text inside a textbox on focus

I'm after the following functionality:

  • user clicks on or tabs into a textbox
  • all text in the textbox is selected, unless the textbox already had focus, in which case the default clicking/selecting functionality should occur

Is this possible?


This works in Firefox 5
$('input[type="text"]').live('focus', function () {
    this.select();
});

http://jsfiddle.net/HmQxZ/13/

Chrome and IE8 selects all the text for only a split second


This works* in Chrome
$('input[type="text"]').live('click', function () {
    this.select();
});

http://jsfiddle.net/HmQxZ/12/

Firefox and IE8 selects all text but upon subsequent clicking, the text remains selected.

*kind of works, after textbox has focus, clicking on it alternates between selecting all text and being able to click where the blinking caret goes. This is probably acceptable.

like image 533
ajbeaven Avatar asked Jul 27 '11 23:07

ajbeaven


1 Answers

Just delay it by a millisecond with setTimeout:

$('input[type="text"]').live('focus', function() {
    var inp = this;
    setTimeout(function() {
        inp.select();
    }, 1);
});

http://jsfiddle.net/HmQxZ/14/

What's happening is some other browser event is setting the selection after you've selected the text. So, by waiting a millisecond, you let all the browser events finish, and then select the text. Nothing will undo it now.

like image 80
gilly3 Avatar answered Nov 14 '22 23:11

gilly3