Automatically Set Focus on a Textbox (Input Box) in AngularJS using ng-click and ng-init

← PrevNext →

Let us assume, you have a form with many input boxes or textboxes and you want set focus on a textbox automatically with the click of a button or after selecting or entering some value in the previous input box. You can this in AngularJS and I’ll show you with few examples on how to set focus automatically on a textbox or input box using AngularJS ng-click directive and ng-init directive.

I am sharing two different examples here. In the first example, I’ll use the ng-click directive and in next I’ll use AngularJS ng-init directive. The principle is the same in both the examples.

In the first example, I have two Input boxes of type text and number and a button control. The button’s click event will call a function in my controller to set focus on the textbox (with the number type).

The second example, I have a jQuery Datepicker control. When I select a date, it would automatically set focus on an Input box (textbox).

First Example - Set Focus on an Input box using AngularJS ng-click

The Markup and the Controller

Look carefully at the controls. I have two <input> boxes. The first is of type text and second is of type number. Both the elements have unique ids. You can add any type of <input> box for this example to work.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>

<body>
    <div ng-app="myApp" 
        ng-controller="myController">

        <p>Enter your name: <input type="text" id="name" /></p>
            <p><button ng-click="setFocus()" id="bt">Click to Set Focus</button></p>
        <p>Enter your age: <input type="number" id="age" /></p>
    </div>
</body>

<script>
    var myApp = angular.module('myApp', []);
    myApp.controller('myController',
        function ($scope, $window) {

            $scope.setFocus = function () {
                var name = $window.document.getElementById('name');
                var age = $window.document.getElementById('age');
                if (name.value != '')
                    age.focus();
                else {
                    alert('Invalid name');
                    name.focus();
                }
            };
        });
</script>
</html>
Try it

If you have worked with JavaScript, you will find it easy to understand. I am sure the method getElementById() looks familiar to you. In my controller function, I have two objects as $scope and $window.

I have attached a method called setFocus() to the $scope. Here in this method (or function), I’ll check for values in the first <input> box (the name).

In the above markup section, I have declared the ng-click directive to a button control, with an expression setFocus(). When you click the button, it calls setFocus() method in the controller.

The AngularJS $window object provides the method getElementById(). I have declared two variables one each for name and age.

var name = $window.document.getElementById('name');
var age = $window.document.getElementById('age');

I’ll check if the name field has a value. If yes, I’ll set focus on the age field, or the focus remains the in the first (name) field.

age.focus();

Second Example - Set Focus on an Input box using AngularJS ng-init

In my second example, I am using a jQuery Datepicker control (it’s a widget) attached to an <input> box. What I am trying to show here is, when you select a date, it would automatically set focus on another <input> box.

I also have a condition that set focus only when you select a date. Else, the next <input> box remains hidden.

The Markup and the Controller
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>

<body>
    <div ng-app="myApp" 
        ng-controller="myController">

        <p>
            <input type="text" id="date" datepicker ng-model="datevalue" 
                placeholder="Select a date" />
        </p>
        <p ng-if="datevalue" ng-init="setFocus()">
            <input type="text" placeholder="Enter some value" id="t" />
        </p>
    </div>
</body>

<script>
    var myApp = angular.module('myApp', []);
    myApp.controller('myController',
        function ($scope, $window) {

            $scope.setFocus = function () {
                var someElement = $window.document.getElementById('t');
                someElement.focus();
            };
        });

    myApp.directive("datepicker", function () {
        function link(scope, element, attrs, controller) {
            element.datepicker({
                onSelect: function (dt) {
                    scope.$apply(function () {
                        controller.$setViewValue(dt);
                    });
                },
                dateFormat: "dd/mm/yy"
            });
        }
        return { require: 'ngModel', link: link };
    });
</script>
</html>
Try it

The principle is the same here. Except, the I am calling the setFocus() method using AngularJS ng-init directive.

The second <p> element has ng-if directive along with ng-init.

<p ng-if="datevalue" ng-init="setFocus()">
    <input type="text" placeholder="Enter some value" id="t" />
</p>

The directive ng-if evaluates an expression based on true or false. If true that is, when you select a value from the Datepicker, it will show the <p> element and that will initiate the setFocus() method in the controller (attached with $scope object).

See the code. I am not checking any condition, since ng-if evaluates the expression.

Well, that’s it. Today you have learn two simple ways to set focus automatically on an <input> box of any type in AngularJS using two different methods. I am sure there are other ways to do this. If you know one, do share it with us here.

Thanks for reading.

← PreviousNext →