我正在使用AngularJs。我有一个下拉列表,我想点击提交按钮进行验证。下拉列表定义如下:
<select name="userTypeSelect" ng-model="selecteduserType" ng-options="user.UserTypeName for user in users" ng-change="updateImageUrl(selectedUserType)">
<option value="">-- Select the User --</option>
</select>
提交按钮定义如下:
<input type="submit" value="Submit" ng-click="add()" />
选项-- Select the User -
是下拉菜单中的第一个选项。我想检查用户是否没有选择任何内容或选择-- Select the User --
,我想在点击提交按钮时显示验证。
如何检查下拉列表是否有正确的数据,而不是在用户点击提交按钮时为空。
答案 0 :(得分:0)
只需检查条件<{p>中的$scope.selecteduserType.length
$scope.add(){
if($scope.selecteduserType.length){
}
else{
alert("pls select a value");
}
}
OR
<form name="myForm" >
<select name="userTypeSelect" ng-model="selecteduserType" ng-options="user.UserTypeName for user in users" ng-change="updateImageUrl(selectedUserType)" required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.userTypeSelect.$error.required">Select service</span>
<input type="submit" ng-disable="myForm.$invalid" value="Submit" ng-click="add()" />
</form>
答案 1 :(得分:0)
只需将:
添加到required
,然后Angular将验证是否选择了除默认值之外的选项。这是一个简单的例子来展示它的实际效果:
<select>
&#13;
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.options = [{
id: 1,
text: 'First Option'
}, {
id: 2,
text: 'Second Option'
}, {
id: 3,
text: 'Third Option'
}, {
id: 4,
text: 'Fourth Option'
}, {
id: 5,
text: 'Fifth Option'
}];
});
&#13;
答案 2 :(得分:0)
尝试这个工作演示,它将按照您的期望工作。
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
$scope.users = [{
id: 1,
name: 'user1'
}, {
id: 2,
name: 'user2'
}, {
id: 3,
name: 'user3'
}];
$scope.add = function() {
console.log("submitting");
};
$scope.changeOption = function() {
$scope.submitted = false;
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="myForm" ng-submit="myForm.$valid && add()" novalidate>
<span ng-show="submitted == true && myForm.userTypeSelect.$error.required">User type select is required.</span>
<select name="userTypeSelect" ng-model="selecteduserType" ng-options="user.id as user.name for user in users" ng-change="changeOption()" required>
<option value="">Select Service</option>
</select>
<input type="submit" value="Submit" ng-click="submitted=true"/>
</form>
</div>
&#13;