首页 > 解决方案 > 在删除所选项目(使用退格)时,下拉列表仅在 select2 rails 中显示已删除的项目

问题描述

我在rails中有一个多选的select2下拉菜单。目前,当我从 lis 中选择一些 2-3 个选项时,当我单击退格键时,所选元素将被删除,并且显示所有选项的下拉列表。但是当我输入一些首字母然后从列表中选择然后单击退格键时,下拉列表正在填充刚刚删除的选项。有没有办法在输入然后选择时,下拉列表将在单击退格键时显示完整列表?我正在使用的代码是(根据 https://github.com/select2/select2/issues/3354#issuecomment-132389291):

$.fn.select2.amd.require(['select2/selection/search'], function (Search) {
  var oldRemoveChoice = Search.prototype.searchRemoveChoice;
  Search.prototype.searchRemoveChoice = function () {
    oldRemoveChoice.apply(this, arguments);
    this.$search.val('');
  };

  $.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
    $('#reports_employee_id').select2({
      matcher: oldMatcher(matchStart),
      templateResult: formatSearch,
      templateSelection: formatSelected,
      maximumSelectionLength: 25,
      placeholder: " "
    })
  });
});

提前致谢 !!

标签: javascripthtmlruby-on-railsjquery-select2

解决方案


好的,我理解这个问题。我需要处理更改。下面我附上更新的代码以供参考。

$.fn.select2.amd.require(['select2/selection/search'], function (Search) {
  var oldRemoveChoice = Search.prototype.searchRemoveChoice;
  Search.prototype.searchRemoveChoice = function () {
    oldRemoveChoice.apply(this, arguments);
    this.$search.val('');
    this.handleSearch();
  };

  $.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
    $('#reports_employee_id').select2({
      matcher: oldMatcher(matchStart),
      templateResult: formatSearch,
      templateSelection: formatSelected,
      maximumSelectionLength: 25,
      placeholder: " "
    })
  });
});

只需要添加这一行:

this.handleSearch();

它按预期工作。


推荐阅读