Reputation: 1414
Trying to do a form validation, when input is empty upon submission it should focus on that empty field. I'm looping through the element.class to do .focus() but I don't know how to find which one is empty and to focus on that field.
var refocusInput = function() {
$timeout(function(){
var inputHasError = document.getElementsByClassName("form-control");
for (var i = 0; i < inputHasError.length; i++) {
var element = inputHasError[i];
if(element){
console.log(inputHasError);
inputHasError[i].focus();
console.log('focus')
}
}
})
}
vm.publishForm = function (){
refocusInput();
}
Upvotes: 0
Views: 1088
Reputation: 2010
you are using angular therefore you can always use the ng-form
attribute and the $valid
property
the example is from angular documentation link
angular.module('formExample', [])
.controller('FormController', ['$scope',
function($scope) {
$scope.userType = 'guest';
$scope.submit = function(e) {
$scope.isValid = $scope.myForm.$valid
}
}
]);
.my-form {
transition: all linear 0.5s;
background: transparent;
}
.my-form.not-valid{
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="formExample">
<form name="myForm" ng-controller="FormController" ng-class="{'not-valid' : !isValid}" class="my-form">
userType:
<input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span>
<input type='button' ng-click='submit($event)' value='submit' />
<br>
<code>userType = {{userType}}</code>
<br>
<code>myForm.input.$valid = {{myForm.input.$valid}}</code>
<br>
<code>myForm.input.$error = {{myForm.input.$error}}</code>
<br>
<code>myForm.$valid = {{myForm.$valid}}</code>
<br>
<code>myForm.$error.required = {{!!myForm.$error.required}}</code>
<br>
</form>
</div>
Upvotes: 1