Angular JS dropdown list select "Others" option and Others input become mandatory

682 Views Asked by At

I am trying to add a dropdown list with "Others" option. If user select "Others", Others (Please specify) input box will become Mandatory. How should I validate this case? Right now I added Javascirpt code to valid this. Is there anyway to do this like "Please specify other reason."?

<form name="myForm">

    <div ng-app="myApp" ng-controller="myCtrl">

    Reason : <select ng-model="reason" ng-options="x for x in names" required></select>    <span ng-show="myForm.reason.untouched">The reason is required.</span>

<p>Others (specify): <input type="text" ng-model="others"></p>


    </div>
    </form>




    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.names = ["reason1", "reason2", "reason3","Others"];

$scope.addItem = function () {

     if ($scope.reason == "Others" && !$scope.others)
     {
         window.alert("Please specify others");
     }

     if($scope.others && $scope.reason!='Others')
     {
         window.alert("Please select reason others");
     }


    });
    </script>
1

There are 1 best solutions below

0
Nickel On

Angular has an ng-required property that allows you to set it conditionally.

<form name="myForm">

<div ng-app="myApp" ng-controller="myCtrl">

Reason : <select ng-model="reason" ng-options="x for x in names" required>
</select>    <span ng-show="myForm.reason.untouched">The reason is required.
</span>

<p>Others (specify): <input type="text" ng-model="others" ng-required="reason == 'Others'"></p>


</div>
</form>