I need to switch focus between fields if user press enter. And if both fields(login & pwd) are not empty $scope.submit Is called. The question is how can I switch focus between this two fields? I can do it using document.getElementByid
, but If there is no id attr? How can I get in angularjs html tag with ng-model to set focus?
JS:
app.controller('loginCtrl', function($scope, $location, $rootScope,$http){
$scope.username = '';
$scope.password = '';
$scope.enter=function(){
if ($scope.username!="" && ($scope.password=="" || $scope.password==undefined)) document.getElementById("password").focus();
else if($scope.password!="" && ($scope.username=="" || $scope.username==undefined)) document.getElementById("username").focus();
else if($scope.password!="" && $scope.username!="") $scope.submit();
};
$scope.submit=function(){
var data={};
data.login=$scope.username;
data.pwd=$scope.password;
$http.post("authorization.php", data).then(function success (response) {
console.log(response);
if (response.data['loggin'] === true) {
$rootScope.loggedIn = true;
$location.path('/dashboard');
$rootScope.name = response.data['name'];
}
else {
$scope.username = '';
$scope.password = '';
}
},function error (response){
console.log(response);
}
);
}
});
HTML:
<div ng-controller="loginCtrl" class="login">
<form action="/" id="myLogin" method="post">
<input type="text" name="username" id="username" ng-model="username" placeholder="Username" required="required" class="input-txt" ng-keyup="$event.keyCode == 13 ? enter() : null"><br>
<input type="password" name="password" id="password" ng-model="password" placeholder="Password" required="required" class="input-txt" ng-keyup="$event.keyCode == 13 ? enter() : null"><br>
<br>
<button type="button" ng-click="submit()" class="btn btn--right">Login</button>
</form>
</div>