简体   繁体   中英

Bootstrap - On selection change in dropdown, make the text control mandatory

I have a select control and a text control in my form. When there is a change in the selection (when user selects a particular value), i want the text control to be made mandatory. This text control should not be mandatory when the form is opened. Is this possible?

Am using bootstrap 3 and AngularJS. And am a newbie to both.

here is my code:

<div class="form-group">
    <label class="col-sm-2 control-label">Select an Option</label>
    <div class="col-sm-4">
        <select class="form-control" name="type">
            <option value="A">Option A</option>
            <option value="B">Option B</option>
        </select>
    </div>
    <div class="col-sm-4">
        <input type="text" class="form-control" name="text" id="text" ng-model="text" >
        <span class="help-block" style="color:red" ng-show="myform.text.$dirty && myform.text.$invalid">
            <span ng-show="myform.text.$error.required">Required, when Option B is selected</span>
        </span>
    </div>
</div>

By default "option A" will be selected, when the user selects "Option B", i want my text control to be made mandatory. This will not be mandatory when the form is opened

Any help is much appreciated

I would use ng-change in your select box to set a $scope property that will toggle the value of ng-required in your text field.

The select box:

<select class="form-control" name="type" ng-model="optionValue" ng-change="setRequired()">
              <option value="A">Option A</option>
              <option value="B">Option B</option>
            </select>

The text field:

<input type="text" class="form-control" name="text" id="text" ng-model="text" ng-required="textRequired" />

The controller:

function mainController($scope) {
      $scope.optionValue = 'A';
      $scope.textRequired = false;
      $scope.setRequired = function() {
          if($scope.optionValue==='B') {
              $scope.textRequired= true;
          }
          else {
              $scope.textRequired = false;
          }
      }
  }

http://plnkr.co/edit/lyMgKIEJukpgnA31hnTz?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM