gpt4 book ai didi

javascript - 使用选项卡 : jump to first invalid tab 的表单验证

转载 作者:行者123 更新时间:2023-11-30 17:38:46 24 4
gpt4 key购买 nike

这是问题 Validation in a form with tabs using nested ng-forms 的后续问题.

在这个 JSFiddle http://jsfiddle.net/gaby/LRfrY/4/我们有一个表单,除非它的所有子表单都是 $valid,否则不会提交。如何在用户尝试提交时跳转到第一个无效选项卡?

最佳答案

我认为使用指令会更好,因为您将接触到 DOM,还因为您可以将此表单所需的所有逻辑集中在一个地方(当您的应用程序增长时,您会感谢它)并且表格也变得更加便携。

我稍微改变了表单,现在它只使用一个 ngForm 并且选项卡是普通的 div。表单及其输入被赋予了名称,因为 ngForm 指令需要它们来创建 formController 对象。

该指令正在监听提交按钮上的点击,我们使用 formController 对象来检查错误并做出相应的 react 。

.directive('myForm', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs) {

var inputs = elm.find('input'), //get all form inputs
inputTab1 = inputs[0], //asign each input to a var
inputTab2 = inputs[1],
submit = inputs[2];

scope.msg='not submitted';
scope.tab=1

//*** ng-form will create a scope var called myForm (myForm is the form's name)

angular.element(submit).bind('click', function (event) {

if(scope.myForm.$valid) {
//form is valid let it submit
scope.$apply(function () {
scope.msg = 'submited';
});
}else {
//form has erros
//event.preventDefault();

if(scope.myForm.tab1.$invalid) {
scope.$apply(function () {
scope.tab = 1;
inputTab1.focus();
});
}else if(scope.myForm.tab2.$invalid) {
scope.$apply(function () {
scope.tab = 2;
inputTab2.focus();
});
}
}
});
}
};
});

这是 fiddle

如果你想深入了解 Angular 的表单,我推荐 this tutorial .

关于javascript - 使用选项卡 : jump to first invalid tab 的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21483579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com