Nitin Kumar Nitin Kumar - 2 months ago 5
AngularJS Question

Angular Js Textbox not focus on button click

Unable to focus on textbox on button click:

<html ng-app="CommonApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="HeadCtrl" ng-init='username=""'>
<input id="UserName" type="text" class="login_boxdecor" ng-model="username" />
<div class="login_btn_outer">
<div class="login_btn_outer2" ng-click="cLgn();">
<a class="btn">Login</a>
</div>
</div>
</body>
</html>
var myApp = angular.module('CommonApp', []);
myApp.controller('HeadCtrl', function($scope){
$scope.cLgn= function(){
if($scope.username.trim().length==0)
{
//Here How to focus my textbox
}
};
});

Answer
<html ng-app="CommonApp">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="HeadCtrl" ng-init='username=""'>
    <input id="UserName" type="text" class="login_boxdecor" ng-model="username" />
    <div class="login_btn_outer">
        <div class="login_btn_outer2" ng-click="cLgn();">
            <a class="btn">Login</a>
        </div>
    </div>
</body>
</html>
var myApp = angular.module('CommonApp', []);
    myApp.controller('HeadCtrl', function($scope){
        $scope.cLgn= function(){
            if($scope.username.trim().length==0)
            {
                document.getElementById("UserName").focus();
            }
        };
    });
Comments