如何使用jquery选择选项时显示相关的div?

时间:2016-09-23 17:12:02

标签: javascript jquery html html-select

我在select中有多个选项。如果选择了选项,则会显示特定的<div>

这是我的HTML。

$(function() {
  $("#reports").change(function() {
    if ($("#subjects").is(":selected")) {
      $("#subjects_form").show();
      $("#classes_form").hide();
      /* ... */
    }
    if ($("#classes").is(":selected")) {
      $("#classes_form").show();
      $("#subjects_form").hide();
      /* ... */
    }
    if (...) {
      ...
    } else {
      $("#subjects_form").hide();
      $("#classes_form").hide();
      ...
    }
  }).trigger('change');
});
.form { display: none }
<select class="form-control" id="reports">
  <option selected="selected" disabled="disabled" value="">Select Report to print</option>
  <option value="subjects" id="subjects">Subjects</option>
  <option value="classes" id="classes">Classes</option>
  <option value="teachers" id="teachers">Teachers</option>
  <option value="students" id="students">Students</option>
  <option value="departments" id="departments">Departments</option>
</select>

<div class="form" id="subjects_form">Subjects</div>
<div class="form" id="classes_form">Classes</div>
<div class="form" id="teachers_form">Teachers</div>
<div class="form" id="students_form">Students</div>

但是上面的代码仅适用于最后一个选项。

2 个答案:

答案 0 :(得分:2)

Id不是<option>代码的有效属性。使用value属性而不是id并选择相关的div。

$("#reports").change(function() {
    $(".form").hide();
    $("#" + this.value + "_form").show(); 
}).trigger('change');
.form { display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="reports">
  <option selected disabled value="">Select Report to print</option>
  <option value="subjects">Subjects</option>
  <option value="classes">Classes</option>
  <option value="teachers">Teachers</option>
  <option value="students">Students</option>
  <option value="departments">Departments</option>
</select>

<div class="form" id="subjects_form">Subjects</div>
<div class="form" id="classes_form">Classes</div>
<div class="form" id="teachers_form">Teachers</div>
<div class="form" id="students_form">Students</div>
<div class="form" id="departments_form">Departments</div>

答案 1 :(得分:0)

您必须使用else if语句来嵌套您的条件,否则您将始终沿着第一个if运行最后一个条件。

$(function() {
      $("#reports").change(function() {
        if ($("#subjects").is(":selected")) {
          $("#subjects_form").show();
          $("#classes_form").hide();
          ...
        }
        else if ($("#classes").is(":selected")) {
          $("#classes_form").show();
          $("#subjects_form").hide();
          ...
        }
        else if (...) {
          ...
        } 
        else {
          $("#subjects_form").hide();
          $("#classes_form").hide();
          ...
        }
      }).trigger('change');
    });