我正在尝试创建一个具有多个下拉选项的表单,可以切换其他字段。
因此,如果下拉列表1选择了“切换”,我只希望“切换字段1”出现,而下拉列表2则相同。我尝试通过在代码中添加各种this
来限制选择器。
$('.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>
答案 0 :(得分:1)
使用siblings:获取匹配元素集中每个元素的兄弟元素,可选择通过选择器进行过滤。
$(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>