Randheer Singh Chouhan Randheer Singh Chouhan - 3 months ago 19
AngularJS Question

Angularjs drop down validation not working

Here is the code snippet:

<select name="userSchool" id="userSchool" ng-model="data.model" ng-init="data.model='0'" required>
<option value="0">Select School</option>
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>



<md-button type="submit" class="md-raised md-accent submit-button" aria-label="Sign up"
ng-disabled="signupForm.$invalid || signupForm.$pristine" ng-click="signupNow()">
SIGN UP
</md-button>


I'm just simple using required as like first name which is

<input type="text" name="firstName" ng-model="vm.form.firstName" placeholder="Enter first name"
required>


it works fine with first name but not userSchool.

Please suggest.

Lex Lex
Answer

Since you have initialized it with a value the required attribute has been fulfilled. You need to use an option with no value and get rid of the ng-init in order for the required validation to work properly.

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.data = {};
    $scope.data.model = undefined;
    $scope.data.availableOptions = [{
      id: 1,
      name: 'School 1'
    }, {
      id: 2,
      name: 'School 2'
    }, {
      id: 3,
      name: 'School 3'
    }];
    $scope.submit = function() {
      console.log('submitted: ', $scope.data.model);
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<form name="theForm" ng-app="app" ng-controller="ctrl" ng-submit="submit()">
  <select name="userSchool" id="userSchool" ng-model="data.model" required>
    <option value="">Select School</option>
    <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  </select>
  <input type="submit" value="Submit">
</form>