0

I have a select that is connected with another one, when there is a selection on the first one the second one becomes required, I am doing that by jquery on the controller

<select id="month-selector" name="month" ng-change="controller.setRequired()">
</select>
<select id="year-selector" name="year">
</select>

//controller
$("#year-selector").prop('required', true);

On my form I have an add button which is enable/disable according with the form validity

<button ng-disabled="!controller.myForm.$valid">
    Add
</button>

So when I select an option on the first select I want the button to be disable until I choose an option on the second select, I have tried setting the second select on the dirty state in order to trigger the form invalidity but it didn't work.

//controller
$("#year-selector").prop('required', true);
myForm.customerSinceYear.$setDirty();

2 Answers 2

1

you can use ng-required on the second select element to only be required when the first has a value

<select id="month-selector" name="month" ng-model="contorller.month">
</select>
<select id="year-selector" name="year" ng-required="controller.month">
</select>
Sign up to request clarification or add additional context in comments.

Comments

1

try this

function TestController($scope) {
  
  $scope.required = false;
  $scope.setRequired = function(){
    $scope.required = true;
    }
  
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-controller="TestController" >
  <form name="myForm">
    <select id="month-selector" name="month" ng-model="month" ng-change="setRequired()" required>
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
   </select>
   <select id="year-selector" ng-model="year" ng-required="required">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
   </select>
    <button ng-disabled="myForm.$invalid">
     Add
    </button>
 </form>
</div>

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.