jquery input select all on focus

Solution 1:

Try using click instead of focus. It seems to work for both mouse and key events (at least on Chrome/Mac):

jQuery < version 1.7:

$("input[type='text']").click(function () {
   $(this).select();
});

jQuery version 1.7+:

$("input[type='text']").on("click", function () {
   $(this).select();
});

Here is a demo

Solution 2:

I think that what happens is this:

focus()
   UI tasks related to pre-focus
   callbacks
       select()
   UI tasks related to focus (which unselect again)

A workaround may be calling the select() asynchronously, so that it runs completely after focus():

$("input[type=text]").focus(function() { 
    var save_this = $(this);
    window.setTimeout (function(){ 
       save_this.select(); 
    },100);
});

Solution 3:

I think this is better solution. Unlike simply selecting in onclick event, it doesn't prevent selecting/editing text with mouse. It works with major rendering engines including IE8.

$('input').on('focus', function (e) {
    $(this)
        .one('mouseup', function () {
            $(this).select();
            return false;
        })
        .select();
});

http://jsfiddle.net/25Mab/9/

Solution 4:

There are some decent answers here and @user2072367 's is my favorite, but it has an unexpected result when you focus via tab rather than via click. ( unexpected result: to select text normally after focus via tab, you must click one additional time )

This fiddle fixes that small bug and additionally stores $(this) in a variable to avoid redundant DOM selection. Check it out! (:

Tested in IE > 8

$('input').on('focus', function() {
    var $this = $(this)
        .one('mouseup.mouseupSelect', function() {
            $this.select();
            return false;
        })
        .one('mousedown', function() {
            // compensate for untriggered 'mouseup' caused by focus via tab
            $this.off('mouseup.mouseupSelect');
        })
        .select();
});