具有相同选项的多个选择框 – 需要唯一选择

我有一个带有3个选择框的表单。 每个选择框都有相同的选项。 我想要你必须为每个选择框选择一个不同的选项。 例如,让我们说选项是“猫”,“狗”和“鸟”。 如果有人在第一个选择框中选择“鸟”,我想从其他两个框中禁用或隐藏该选项。 如果他们改变了他们的选择,那么“鸟”将再次启用或取消隐藏。

 Cat Dog Bird   Cat Dog Bird   Cat Dog Bird  

我假设我可以使用jquery onchange执行此操作,但我不确定如何在不同的选择框中要求唯一选择。

 $('select').on('change', function() { // If option is selected, disable it in all other select boxes. If option is deselected, reenable it in all other select boxes. }) 

谢谢你的帮助!

1)从上到下优先级方法

流量必须从上到下 。 这也意味着当用户更改下拉列值时,必须重置所有下一个下拉列表。 话虽如此,这是我的代码片段。

 HandleDropdowns($('#box1')); //initially call this function to handle the dropdowns by passing the first dropdown as parameter $('select').on('change', function() { HandleDropdowns($(this)); // handle all dropdowns on any change event. }); function HandleDropdowns(element) { var $element = element; var value = $element.val(); $element.nextAll().val(''); //using nextAll lets reset all the following dropdowns $element.nextAll().attr('disabled', 'disabled'); //disable all the following dropdowns. HandleOptions(); // call this function to toggle the options if (value.length) { $element.next().removeAttr('disabled'); // only if this dropdown has some selection enable the next dropdown. } } function HandleOptions() { $('option').removeAttr('disabled'); //reset all the options to be available $.each($('select'), function() { //loop from top to bottom and disable the options one by one. var value = $(this).val(); if (value.length) { $(this).nextAll().find('option[value="' + value + '"]').attr('disabled', 'disabled'); } }); } 
     

试试这个

 $('select').on('change', function () { $("select").find("option").removeAttr("disabled"); $("select").not(this).find("option[value=" + $(this).val() + "]").attr("disabled", "disabled"); }); 

您可以使用onchange侦听器并同时评估结果。 还要添加一个复位按钮,一旦三个被选中,它就变成了瓶颈。

工作代码如下

 function changeSelect(elements) { var values = {}; elements.forEach(function(item){ values[item.id] = item.value; }); elements.forEach(function(item){ for(var i = 0; i < item.children.length; i++) { for(ids in values) { if(item.id != ids && item.children[i].value == values[ids]) { item.children[i].style.display = 'none'; } } } }); } function resetSelection(elements) { elements.forEach(function(item){ item.value = ''; for(var i = 0; i < item.children.length; i++) { item.children[i].style.display = ''; } }); } var box1 = document.getElementById('box1'); var box2 = document.getElementById('box2'); var box3 = document.getElementById('box3'); var boxArray = [box1, box2, box3]; boxArray.forEach(function(item){ item.addEventListener('change', changeSelect.bind(undefined,boxArray)); }); document.getElementById('reset').addEventListener('click', resetSelection.bind(undefined,boxArray));