尝试进行表单验证,当提交时输入为空时,应该关注该空字段。我循环遍历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();
}
答案 0 :(得分:1)
您正在使用角度,因此您始终可以使用ng-form
属性和$valid
属性
示例来自角度文档 link
angular.module('formExample', [])
.controller('FormController', ['$scope',
function($scope) {
$scope.userType = 'guest';
$scope.submit = function(e) {
$scope.isValid = $scope.myForm.$valid
}
}
]);
&#13;
.my-form {
transition: all linear 0.5s;
background: transparent;
}
.my-form.not-valid{
background: red;
}
&#13;
<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>
&#13;