zsly zsly - 23 days ago 20
jQuery Question

Jquery reusable form toggle

I'm trying to create a form that has multiple dropdown selects, which can toggle additional fields.

So, if dropdown 1 has "toggle" selected I only want "toggled field 1" to appear and the same thing for dropdown 2. I tried limiting the selector by adding various

this
to my code.



$('.dropdownToggle').change(function() {
selection = $(this).val();
switch (selection) {
case 'toggle':
$('div.toggle').show();
break;
default:
$('div.toggle').hide();
break;
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>Dropdown 1</label>
<select class="dropdownToggle" style="width: 67%;">
<option value="something">Something</option>
<option value="toggle">Toggle</option>
</select>
<div class="toggle" style="display: none;">
<label>toggled field 1</label>
<input type="text" placeholder="" style="width: 67%;">
</div>
</div>

<div>
<label>Dropdown 2</label>
<select class="dropdownToggle" style="width: 67%;">
<option value="something">Something</option>
<option value="toggle">Toggle</option>
</select>
<div class="toggle" style="display: none;">
<label>toggled field 2</label>
<input type="text" placeholder="" style="width: 67%;">
</div>
</div>




Answer

use siblings: Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

$(this).siblings(".toggle").show();

        $('.dropdownToggle').change(function() {
          selection = $(this).val();
          switch (selection) {
            case 'toggle':
             $(this).siblings(".toggle").show();
              break;
            default:
              $(this).siblings(".toggle").hide();
              break;
          }
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label>Dropdown 1</label>
  <select class="dropdownToggle" style="width: 67%;">
            <option value="something">Something</option>
            <option value="toggle">Toggle</option>
          </select>
  <div class="toggle" style="display: none;">
    <label>toggled field 1</label>
    <input type="text" placeholder="" style="width: 67%;">
  </div>
</div>

<div>
  <label>Dropdown 2</label>
  <select class="dropdownToggle" style="width: 67%;">
            <option value="something">Something</option>
            <option value="toggle">Toggle</option>
          </select>
  <div class="toggle" style="display: none;">
    <label>toggled field 2</label>
    <input type="text" placeholder="" style="width: 67%;">
  </div>
</div>

Comments