kcNeko kcNeko - 2 months ago 8
HTML Question

How to show relevant div when option selection using jquery?

I have multiple options in a select. If the select option is selected, a specific

<div>
will show.

Here's my 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>


However the code above only works with the last option.

Answer

Id isn't valid attribute for <option> tag. Use value attribute instead of id and select relevant div by it.

$("#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>