删除选择框的所有选项,除了第一个选项 [英] removing all options of select box except 1st option
问题描述
在以下情况下,我试图清空选择选项:
I'm trying to empty select options when:
已选择id"mClick",id的"sClick","cClick"和"srClick"将被清空.
id "mClick" is selected, id's "sClick", "cClick" and "srClick" will be emptied.
已选择id"sClick",id的"cClick"和"srClick"将被清空.
id "sClick" is selected, id's "cClick" and "srClick" will be emptied.
已选择ID"cClick",ID"srClick"将被清空.
id "cClick" is selected, id "srClick" will be emptied.
<form action="javascript:void(0);" method="POST" id="lForm">
<table>
<tr>
<td>
<select name="module" id="mClick">
<option value="">Select Mod</option>
<option value="1">Mod 1</option>
<option value="2">Mod 2</option>
<option value="3">Mod 3</option>
</select>
</td>
<td>
<select name="state" id="sClick">
<option value="">Select State</option>
<option value="1">State 1</option>
<option value="2">State 2</option>
</select>
</td>
<td>
<select name="city" id="cClick">
<option value="">Select City</option>
<option value="1">City 1</option>
<option value="2">City 2</option>
</select>
</td>
<td>
<select name="services" id="srClick">
<option value="">Select Services</option>
<option value="1">Services 1</option>
<option value="2">Services 2</option>
</select>
</td>
</tr>
</table>
在场景3中,我使用了此功能,但它删除了所有功能,但最后一次选择除外.任何想法就是我所缺少的吗?谢谢
in scenario 3, i used this function, but it deleted all, except the last select. Any idea's what i'm missing? Thanks
$('#lForm select[id!="mClick"] select[id!="sClick"] select[id!="cClick"] option[value!=""]').remove().end();
推荐答案
清除描述中的选项的最简单方法是使用options.length = 1
.另外,您可以利用以下事实:每个下拉列表都会清除逻辑上跟随它的下拉列表,因此您只需要声明一个更改处理程序即可.
The easiest way to clear the options in the way you're describing is by using options.length = 1
. Also, you can leverage the fact that each drop down clears the ones that logically follow it, so that you only need to declare a single change handler.
$('#lForm select').on('change', function() {
if (this.selectedIndex > 0) {
var $others = $(this).closest('table').find('select'),
current = $others.index(this); // find current
while (++current < $others.length) {
// for each following drop down
$others.get(current).options.length = 1;
}
}
});
我不确定您将如何重新填充下拉列表:)
I'm not sure how you're going to repopulate the drop downs though :)
这篇关于删除选择框的所有选项,除了第一个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!