简体   繁体   中英

How to make a <div> show only when a certain <select> dropdown option is selected? The <select> options are populated with the ng-repeat directive

I have a select dropdown list populated with the angularjs ng-repeat directive. I would like for a div to show only when a certain option is selected.

Here is the code:

<select type="text"
  class="form-control"
  ng-model="vm.request.requestType"  
  name="requestType" id="requestType"
  placeholder=""
  required>
   <option selected></option>
   <option value="test">test</option>
   <option ng-repeat="requestType in vm.requestTypes">{{requestType}}</option>
</select>

<script>
    $(function() {
      $("#requestType").change(function () {
        if ($("#test").is(":selected")) {
          $("#continueCheckbox").show();
        } else {
          $("#continueCheckbox").hide();
        }
      }).trigger('change');
    });
</script>

<div id="continueCheckbox">
  <input type="checkbox"
     name="continueCheckbox"
     value="continueCheckbox">
     Check this box to continue, and to confirm that you have read the 
     Documentation
</div>

The "test" option is just for testing if the function works. Currently, the checkbox displays no matter what is selected, and never disappears.

I highly recommend not mixing AngularJS and jQuery. Both are DOM manipulation frameworks and do not work well together. Here is one way you could accomplish what you are after with AngularJS:

<div id="continueCheckbox" ng-if="vm.request.requestType === 'test'">
    <input type="checkbox"
           name="continueCheckbox"
           value="continueCheckbox">
        Check this box to continue, and to confirm that you have read the Documentation
</div>

Have you tried using the ng-class directive?

<div id="continueCheckbox" ng-class="selected: vim.request.requestType === 'test'"></div>

Then handle the style in .css file

.selected {
  display: none;
}

If you wanted to use jQuery, you could just check the value of the select. You have it set up already.

var selectType=$(this).val();
if (selectType=="test") // instead of if ($("#test").is(":selected")) 

You could also use vanilla JS with .value to do your comparison.

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