简体   繁体   English

当从另一个 select 中选择了特定选项时,隐藏多个 select 中的选项

[英]Hide an option in a multiple select, when a specific option has been selected from another select

I have seen questions similar to this but mine is different.我见过类似的问题,但我的不同。 so I have these first 2 dropdown menu (data are selected from my database) and another dropdown which is attributed with multiple , now my code works on the first 2 dropdowns but when it comes to the multiple dropdown it's not working.所以我有这前 2 个下拉菜单(数据是从我的数据库中选择的)和另一个属性为multiple的下拉菜单,现在我的代码适用于前 2 个下拉菜单,但是当涉及到multiple下拉菜单时,它不起作用。

here are my dropdown menu;这是我的下拉菜单;

<select class="custom-select" name="option_one">
 <option>test1</option>
 <option>test2</option>

<select class="custom-select" name="option_two">
 <option>test1</option>
 <option>test2</option>

<select id="multiple" class="custom-select" name="option_three[]" multiple="multiple">
 <option>test1</option>
 <option>test2</option>

Here is my javascript这是我的 javascript

$(document).ready(function() {
 function intializeSelect() {
  $('.custom-select').each(function(box) {
   var value = $('.custom-select')[box].value;
   if (value) {
    $('.custom-select').not(this).find('option[value="' + value + '"]').hide();
   }
  });
};
 intializeSelect();
 $('.custom-select').on('change', function(event) {
  $('.custom-select').find('option').show();
 });
});



                    

With a single on change attached to all select, you could check value and hide depending on innerHtml or value ( in your case no value, so checking by text),将单个 on 更改附加到所有 select,您可以检查值并根据 innerHtml 或值隐藏(在您的情况下没有值,因此通过文本检查),

What I've done is first showing all option, then check value if not undefined, if thre were a value hide other options input, that has same text value,我所做的是首先显示所有选项,然后检查值是否未定义,如果有一个值隐藏其他选项输入,具有相同的文本值,

See below working snippet:请参阅下面的工作片段:

 $(document).ready(function() { $('.custom-select').on('change', function(event) { let value = $(this).val(); // show all options of all select $('.custom-select').find("option").show(); // reset values after change of other select $('.custom-select').not(this).val(""); if (value.length > 0) { $('.custom-select').not(this).find("option").filter(function() { return $(this).html() == value; }).hide(); }; }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select class="custom-select" name="option_one"> <option></option> <option>test1</option> <option>test2</option> </select> <select class="custom-select" name="option_two"> <option></option> <option>test1</option> <option>test2</option> </select> <select id="multiple" class="custom-select" name="option_three[]" multiple="multiple"> <option></option> <option>test1</option> <option>test2</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM