当 Select2 使用 minimumInputLength 时清除选择

Clear selection when Select2 uses minimumInputLength

我有一个 select 输入字段,我正在使用 Select2 jQuery 插件对其进行增强。我传递了 minimumInputLength 属性 让用户在填充匹配项之前键入几个字母。但是,如果需要,我不确定用户如何清除 selection。

我尝试通过 allowClear 属性,虽然它确实显示 'X',但按钮不起作用,selection 仍然存在。

编辑:

jsfiddle link: https://jsfiddle.net/8f1u48et/

您需要在初始化 Select2 jQuery 插件时定义一个 placeholder 属性。插件需要它。

更新后的代码如下所示:

$('#members').select2({
  minimumInputLength: 3,
  allowClear: true,
  placeholder: ''
});

您可以在 this JSFiddle 上查看工作示例。选择内容后,单击清除按钮将删除当前选择。

关于这个插件需要 placeholder 的事实,有 a section of the documentation 专门针对这个问题,但目前还没有回答...

如果您需要更好地控制正在发生的事情,the documentation 中提供了 Select2 将在组件生命周期内触发的事件列表。

例如,要将侦听器附加到在删除选择之前触发的 unselecting 事件(例如当您单击清除按钮时),您将使用:

$('#members').on('select2:unselecting', function (evt) {
  // Do something...
});

还有一个恼人的错误,即 Select2 在清除和删除选择时会错误地切换下拉菜单。

此问题记录在 their Github 上,但尚未关闭和修复。此线程中提供了许多解决方法,例如取消 select2:unselect 事件后立即发生的 select2:opening/closing 事件:

var $element = $('#members');

$element.on('select2:unselect', function() {
  function cancelAndRemove(event) {
    event.preventDefault()
    removeEvents()
  }
  function removeEvents() {
    $element.off('select2:opening', cancelAndRemove)
    $element.off('select2:closing', cancelAndRemove)
  }
  $element.on('select2:opening', cancelAndRemove)
  $element.on('select2:closing', cancelAndRemove)
  setTimeout(removeEvents, 0)
});

您可以使用 select2:unselecting 事件,这样当用户单击 X 时,所选的值将被删除并且不再打开 select2 面板:

$(function () {
  $('#members').select2({
    placeholder: "Select a member",
    minimumInputLength: 3,
    allowClear: true
  });

  // when you click on the X....
  $('#members').on('select2:unselecting', function(e) {
    // prevent the default action
    e.preventDefault();
    
    // deselect....
    $('#members').val('');
    
    // inform select2 of deselecting....
    $('#members').trigger('change.select2');
  })
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select id="members" style="width: 100%;">
    <option value="">&nbsp;</option>
    <option value="300001">Daniel Akaka Kahikina</option>
    <option value="300002">Lamar Alexander</option>
    <option value="300003">Wayne Allard A.</option>
    <option value="300004">George Allen Felix</option>
    <option value="300005">John Smith</option>
</select>