Select text on input focus

This is an old answer, for Angular 1.x

Better way to do it is by using the ng-click built-in directive:

<input type="text" ng-model="content" ng-click="$event.target.select()" />

EDIT:

As JoshMB has kindly reminded; referencing DOM nodes in Angular 1.2+ is no longer allowed. So, I've moved $event.target.select() into the controller:

<input type="text" ng-model="content" ng-click="onTextClick($event)" />

Then in your controller:

$scope.onTextClick = function ($event) {
    $event.target.select();
};

Here is an example fiddle.


Here's an enhanced directive which avoids reselecting the text when the user clicks to position the cursor in the input box.

module.directive('selectOnClick', function () {
    return {
        restrict: 'A',
        link: function (scope, element) {
            var focusedElement;
            element.on('click', function () {
                if (focusedElement != this) {
                    this.select();
                    focusedElement = this;
                }
            });
            element.on('blur', function () {
                focusedElement = null;
            });
        }
    };
})

Neither of proposed solutions worked well for me. After quick research I came up with this:

module.directive('selectOnFocus', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var focusedElement = null;

            element.on('focus', function () {
                var self = this;
                if (focusedElement != self) {
                    focusedElement = self;
                    $timeout(function () {
                        self.select();
                    }, 10);
                }
            });

            element.on('blur', function () {
                focusedElement = null;
            });
    }

  }

});

It's a mix of several solutions proposed, but works both on click and focus (think autofocus) and allows manual selection of partial value in the input.


The way to do this in Angular is to create a custom directive which does the autoselect for you.

module.directive('selectOnClick', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function () {
                if (!$window.getSelection().toString()) {
                    // Required for mobile Safari
                    this.setSelectionRange(0, this.value.length)
                }
            });
        }
    };
}]);

Apply the directive like this:

<input type="text" value="test" select-on-click />

View demo

Update1: Removed jQuery dependency.

Update2: Restrict as attribute.

Update3: Works in mobile Safari. Allows selecting part of the text (requires IE>8).