在下拉列表 1 中选择时隐藏下拉列表 2 中的选项 [英] Hide option from dropdown 2 when selected in dropdown 1
问题描述
我有两个下拉菜单,它们都有相同的项目.如果在下拉列表 1 中选择了一个选项,那么我想在下拉列表 2 中隐藏该选项.当它在下拉列表 1 中被取消选择时,我希望它再次出现在下拉列表 2 中,然后选择哪个选项然后隐藏在下拉列表 2 中. 我正在尝试排除第一个索引中的空白选项.
I have two dropdowns, both have the same items in them. If an option is selected in dropdown 1 then I would like to hide that option in dropdown 2. When it is unselected in dropdown 1 I would like it to appear again in dropdown 2 and whichever option is then selected to then be hidden in dropdown 2. I am trying to have this exclude the blank option in the first index.
这是我开始使用的代码笔,但我不知道从哪里开始:
Here is a codepen that I started, but I am not sure where to go from here:
http://codepen.io/cavanflynn/pen/EjreJK
var $dropdown1 = $("select[name='dropdown1']");
var $dropdown2 = $("select[name='dropdown2']");
$dropdown1.change(function () {
var selectedItem = $($dropdown1).find("option:selected").val;
});
感谢您的帮助!
推荐答案
如评论中所说,其中一个选项是根据第一次选择中的选择禁用/启用选项,如下所示.这将适用于所有浏览器,而不是隐藏/显示.
As said in comments, one of the options is to disable/enable options according to the selection in the first select, like below. This would work on all browsers as opposed to hide/show which doesn't.
var $dropdown1 = $("select[name='dropdown1']");
var $dropdown2 = $("select[name='dropdown2']");
$dropdown1.change(function() {
$dropdown2.find('option').prop("disabled", false);
var selectedItem = $(this).val();
if (selectedItem) {
$dropdown2.find('option[value="' + selectedItem + '"]').prop("disabled", true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="dropdown1">
<option></option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
<select name="dropdown2">
<option></option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
另一个选项是通过 根据第一个下拉列表中的选择删除/添加第二个下拉列表中的选项.clone()
,如下.
Another option is to remove/add options in the 2nd dropdown based on the selection in the first via .clone()
, as below.
var $dropdown1 = $("select[name='dropdown1']");
var $dropdown2 = $("select[name='dropdown2']");
$dropdown1.change(function() {
$dropdown2.empty().append($dropdown1.find('option').clone());
var selectedItem = $(this).val();
if (selectedItem) {
$dropdown2.find('option[value="' + selectedItem + '"]').remove();
}
});
这篇关于在下拉列表 1 中选择时隐藏下拉列表 2 中的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!