【发布时间】:2015-08-06 17:45:51
【问题描述】:
我有两个下拉菜单:dropdown1 和 dropdown2。 dropdown2 被禁用开始。您可以使用复选框启用 dropdown2。启用后,您可以在任一下拉列表中选择一个选项,它将在另一个下拉列表中显示为禁用。这是双向的。假设在 dropdown2 中选择了一个选项(因此它在 dropdown1 中被禁用)并且您取消选中该复选框以禁用 dropdown2。我希望随后启用 dropdown1 中的选项,因为 dropdown2 整体上被禁用。当复选框未选中时,我将 dropdown2 的 selectedIndex 设置为 0,但它不起作用。这可能很难理解,所以我做了一个codepen:
http://codepen.io/cavanflynn/pen/mJvzgg
HTML
<select name="dropdown1" id="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" id="dropdown3" class="dropdown-lower">
<option></option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
<input type="checkbox" id="checkbox"/>
Javascript
$(document).ready(function() {
$(".dropdown-lower").prop("disabled", true);
});
$("#checkbox").click(function () {
if ($(this).is(":checked")) {
$(".dropdown-lower").prop("disabled", false);
} else {
$(".dropdown-lower").prop("disabled", true);
document.getElementById("dropdown3").selectedIndex = "0";
document.getElementById("dropdown-operator2").selectedIndex = "0";
document.getElementById("dropdown4").selectedIndex = "0";
}
});
if ($(".dropdown-lower").prop("disabled", false)) {
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);
}
});
$dropdown2.change(function() {
$dropdown1.find('option').prop("disabled", false);
var selectedItem = $(this).val();
if (selectedItem) {
$dropdown1.find('option[value="' + selectedItem + '"]').prop("disabled", true);
}
});
}
【问题讨论】:
-
总是从一张干净的床单开始。当复选框未选中时,重新启用所有选项。
标签: javascript jquery html checkbox