1

I have a following problem with select in my AngularJS application. I have set required attribute but it doesn't work on select tag. Doesn't trigger native validation. Here is my html code:

<div ng-app="app">
    <div ng-controller="testCtrl">
        <form ng-submit="selectChanged()">
        <select ng-model="first" required="required">
            <option>choose</option>
            <option value="2">2</option>
        </select>
            <input type="submit" value="test"/>
        </form>
    </div>
</div>

Here is my controller:

angular.module('app', []).controller('testCtrl', function ($scope) {
    $scope.selectChanged = function () {

    };
});

Here is working jsfiddle: http://jsfiddle.net/zono/k3b5J/3/

Best regards.

3 Answers 3

1

Your code should be:

angular.module('app', []).controller('testCtrl', function ($scope) {
    $scope.first = "";
    $scope.selectChanged = function () {
        alert($scope.first);
    };
});

You didn't add the variable your select is bound to, $scope.first in this case. And the empty option should have a value of "" --> <option value ="">choose</option>

Here is a working fiddle: http://jsfiddle.net/k3b5J/4/

Sign up to request clarification or add additional context in comments.

Comments

1

You need to wire-up form validity with submit button, e.g. so it gets disabled when form is not valid

<div ng-app="app">
    <div ng-controller="testCtrl">
        <form name="myform" ng-submit="selectChanged()">
        <select ng-model="first" required="required">
            <option>choose</option>
            <option value="2">2</option>
        </select>
            <input type="submit" value="test" ng-disabled="!myform.$valid"/>
        </form>
    </div>
</div>

I updated your fiddle to reflect that: http://jsfiddle.net/qt8z3/

Comments

1

The thing is that when option value is not defined, the text is taken as a value, so, when choose is selected, actual value of first should be choose.

Your code can be fixed like this:

<div ng-app="app">
    <div ng-controller="testCtrl">
        <form ng-submit="selectChanged()">
        <select ng-model="first" required="required">
            <option value="">choose</option>
            <option value="2">2</option>
        </select>
            <input type="submit" value="test"/>
        </form>
    </div>
</div>

note value on <option value="">choose</option>

Edit note: when choose is selected, value actually exists, so field is filled and it passes required validation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.