【发布时间】:2016-06-06 07:32:27
【问题描述】:
我有 html 表单,我想在表单启动时保持提交按钮禁用,因为默认情况下它已启用并且即使控件为空也接受输入。 这是我的代码。 一旦您输入数据然后将其从输入控件中删除,它就可以正常工作,但默认情况下它不会。
<html>
<head>
<title>Angular JS Forms</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<form name = "studentForm" novalidate>
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input name = "firstname" placeholder="name" type = "text" ng-model = "firstName" required>
<span style = "color:red" ng-show = "studentForm.firstname.$dirty && studentForm.firstname.$invalid">
<span ng-show = "studentForm.firstname.$error.required">First Name is required.</span>
</span>
</td>
</tr>
<tr>
<td>Enter Domain name: </td>
<td><input name = "domain" type = "text" ng-model = "domain" placeholder="domain" required>
<span style = "color:red" ng-show = "studentForm.domain.$dirty && studentForm.domain.$invalid">
<span ng-show = "studentForm.domain.$error.required">Last Name is required.</span>
</span>
</td>
</tr>
<tr>
<td>Email: </td><td><input name = "email" type = "email" ng-model = "email" placeholder="Email" length = "100" required>
<span style = "color:red" ng-show = "studentForm.email.$dirty && studentForm.email.$invalid">
<span ng-show = "studentForm.email.$error.required">Email is required.</span>
<span ng-show = "studentForm.email.$error.email">Invalid email address.</span>
</span>
</td>
</tr>
<tr>
<td>
<button ng-click = "reset()">Reset</button>
</td>
<td>
<button ng-disabled = "studentForm.firstname.$dirty &&
studentForm.firstname.$invalid || studentForm.domain.$dirty &&
studentForm.domain.$invalid || studentForm.email.$dirty &&
studentForm.email.$invalid" ng-click="submit()">Submit</button>
</td>
</tr>
</table>
</form>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.reset = function(){
}
$scope.reset();
});
</script>
</body>
</html>
【问题讨论】:
-
提交监听器应该在表单上,而不是提交按钮上,因为表单可以在不点击提交按钮的情况下提交。
-
@RobG,我也这么认为,但显然浏览器(至少是 Chrome)不允许您使用,例如,输入,如果提交按钮被禁用。但是,如果省略提交按钮,它确实允许您。 See fiddle。第一个表单不会提交,而第二个表单会。
-
@GolezTrol——至少 Safari 和 Omniweb 可以。无论如何,提交监听器都应该在表单上,因为一旦启用了提交按钮,就可以在所有浏览器(除了一些非常旧的 IE 版本)中不选择提交按钮来提交表单。
标签: javascript html angularjs forms