【问题标题】:Hide an option in a multiple select, when a specific option has been selected from another select当从另一个选择中选择了特定选项时,隐藏多选中的选项
【发布时间】:2021-02-02 08:39:54
【问题描述】:

我见过类似的问题,但我的问题不同。 所以我有这前 2 个下拉菜单(数据是从我的数据库中选择的)和另一个属性为 multiple 的下拉菜单, 现在我的代码适用于前 2 个下拉菜单,但是当涉及到 multiple 下拉菜单时,它不起作用。

这是我的下拉菜单;

<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>

这是我的 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();
 });
});



                    

【问题讨论】:

  • 我已尝试修复您的缩进,但缺少},因此不清楚您的代码应该是什么。不太可能这是没有开始的递归,所以在缩进上猜到了。请更新,最好使用完整的 sn-p [&lt;&gt;] 来演示该问题。
  • @freedomn-m 完成编辑
  • 您的所有选项(如提供的)都没有值,因此$('.custom-select')[box].value 始终为空白。请参阅minimal reproducible examplesn-p。
  • 这是一个解决两件事的小提琴:没有值/没有从更改事件中调用 init(尽管不清楚这是否是一个错误)。除了“它适用于 2”和“它不适用于 3”之外,目前还不清楚您要尝试 实现什么。根据您的要求,什么是“工作”?无论如何,这里是:jsfiddle.net/52gcohmk

标签: javascript php html jquery css


【解决方案1】:

通过对所有 select 附加单个 on 更改,您可以根据 innerHtml 或值检查值并隐藏(在您的情况下没有值,因此通过文本检查),

我所做的是首先显示所有选项,然后检查值是否未定义, 如果有一个值隐藏其他选项输入,具有相同的文本值,

请参阅下面的工作 sn-p :

$(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>

【讨论】:

  • 我复制了代码,但它仍然对我不起作用@Spring
  • @AZUREKNIGHT 你能准确描述一下你需要什么吗?如果在一个选项中选择了选项,您应该将其隐藏在其他选项中吗?是不是多个?
  • 是的,这正是我所需要的,当涉及到多项选择时,我在隐藏所选选项时遇到了困难
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多