Select2 在选择另一个时删除默认选项

Select2 remove default option when another selected

我想让默认选项充当占位符。

我正在 ajax 搜索产品。我希望我的输入框显示 "All",直到我 select 编辑了一个产品。

这将是默认视图:

但是一旦我 select 一个产品,我希望全部消失,只显示产品:

我整理了一个代码笔,希望能让事情顺利进行!

谢谢大家!

https://codepen.io/saltcod/pen/bGdzoGN

HTML:

<div class="container">

  <select class="form-control am-product-selector__product-list-select" name="choices-multiple-default" id="choices-multiple-default" placeholder="All Products" multiple>
    <option value="All" selected>All</option>

  </select>

</div>

和 JS:


const options = [{ id: 1, text: 'All' }];

const select2Instance = jQuery( '#choices-multiple-default' ).select2( {
        placeholder: 'Search products',
        ajax: {
            url: url,
            dataType: 'json',
            delay: 250,

            data: params => {
                return {
                    //term: params.term // search query
                };
            },

            // Process fetched results
            processResults: data => {
                if ( data ) {
                    data.map( item => {
                        options.push( { id: item.id, text: item.title } );
                    } );
                }

                return {
                    results: options
                };
            },
            cache: true
        },
        minimumInputLength: 3 // the minimum of symbols to input before perform a search
    } );

我们可以使用原生 select 元素的 change 事件及其作用域版本 change.select2

在元素上添加 select2 插件时,只要 select 编辑或删除选项,就会触发 change 事件。

因此,当添加异步列表中的选项时,我们应该删除 all 选项。 此外,当所有选项都被删除时(select 没有值),我们应该重新添加 all 选项。 但是我们需要通知 select2 变化,所以我们触发 change.select2 事件。

完整代码为:

select2Instance.on('change', function () {
  const values = $(this).val();
  if (values.length > 1) {
    const index = values.indexOf('all');
    if (index > -1) {
      values.splice(index, 1);
      $(this).val(values);
    }
  } else if (values.length === 0) {
    $(this).val('all');
  }
  $(this).trigger('change.select2'); // Notify only Select2 of changes;
});

Codepen 演示: https://codepen.io/andreivictor/pen/yLNZzbb

有关 Select2 事件的更多信息: