【问题标题】:Multiple select, when one certain option is selected, unselect other options多个SELECT,选择某个选项时,取消选择其他选项
【发布时间】:2017-08-13 00:19:46
【问题描述】:

我的 HTML 中有一个多选列表。如果选择了值 296,则必须取消选择所有其他选项。

这是我正在使用的代码,因此当我想选择多个选项时不必使用 CTRL:

$("#select").mousedown(function(e) {
  e.preventDefault();

  var select = this;
  var scroll = select.scrollTop;

  if (select.value == 296) {
    //unselect all the other options
  }

  e.target.selected = !e.target.selected;

  setTimeout(function() {
    select.scrollTop = scroll;
  }, 0);

  $(select).focus();
}).mousemove(function(e) {
  e.preventDefault()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select" name="adrestype_id" class="form-control" required="required" multiple="multiple">                
    <option value="296">Primairadres </option>                
    <option value="297">Bezoekadres </option>                
    <option value="298">Factuuradres </option>                
    <option value="299">Postadres </option>
</select>

我似乎无法弄清楚如何在选择值296时取消选择所有其他选项

【问题讨论】:

    标签: javascript jquery multipleselection


    【解决方案1】:

    下面似乎实现了你上面所说的。如果已经选择了 296,它也会阻止您选择选项。

    const unselect = '296'
    
    $('#select').change(function() {
      const $el = $(this)
      console.log($el.val())
      if ($el.val().indexOf(unselect) !== -1) {
        $el.children('option').each(function() {
          $opt = $(this)
          if ($opt.val() !== unselect) {
            $opt.prop('selected', false)
          }
        });
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="select" name="adrestype_id" class="form-control" required="required" multiple="multiple">                
                <option value="296">Primairadres </option>                
                <option value="297">Bezoekadres </option>                
                <option value="298">Factuuradres </option>                
                <option value="299">Postadres </option>
            </select>

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 2018-05-18
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多