尝试进行表单验证,当提交时输入为空时,应将重点放在该空白字段上。我正在遍历element.class来执行.focus(),但是我不知道如何找到哪个是空的并专注于该字段。
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();
}
最佳答案
您正在使用角度,因此您始终可以使用ng-form
属性和$valid
属性
该示例来自角度文档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>
关于javascript - Angular 形验证重点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36398997/