如何从Selectize中移除一个项目?

10

有没有办法从Selectize中删除项目?

这是我的一个示例列表:

  1. AMNT
  2. QTY
  3. NA

当我传递 NA 的时候,它应该删除特定的项目:

   $.fn.removeSelectorValue = function (value) {
      var selectize = this[0].selectize;
      selectize.removeItem(value);

      return this;
   };

这个不起作用,有人可以帮我吗?

4个回答

11

removeItem 移除给定值标识的 已选中 项目。若要从列表中移除选项,则应使用 removeOption

示例 - 打开http://brianreavis.github.io/selectize.js/,打开控制台并输入:

$('#select-beast')[0].selectize.removeOption(1)

移除Chuck Tesla作为可选项


我认为它对我不起作用,选项来自枚举的服务器。 - John
如果我理解正确,您想在用户选择选项时从列表中删除该选项,例如当用户选择AMNT时,列表仅包含QTY、NA。如果不是这种情况,请从用户角度解释问题。 - Michał Samujło
我不想删除所选的选项,当onShow时,我有3个来自服务器的列表,但我不想显示这三个列表(qty,amnt,na)。在onShow本身上,我必须移除那个选项。而不是在选择之后。我正在使用Backbone、Marionette和Selectize来实现。我的选择器类似于this.ui.__el_String__xyzSelector()。 - John
这个 xyzSelector 包含一些代码,可以以查找的方式返回列表。 - John
1
这种方法唯一的问题是,如果选定的项目是要删除的项目,则会最小化选择框并且看起来有点错误,请告诉我是否找到了解决方案。 - Tomzan

8
$(document).on('click', 'div.selectize-input div.item', function(e) {
    var select = $('#services').selectize();
    var selectSizeControl = select[0].selectize;
    // 1. Get the value
    var selectedValue = $(this).attr("data-value");
    // 2. Remove the option 
    select[0].selectize.removeItem(selectedValue);

    select[0].selectize.refreshItems();
    select[0].selectize.refreshOptions();

});

这段代码并没有将选项从下拉列表中删除,只是将其从所选选项中删除。


谢谢回复,第一个答案对我很有效。 - John

4

虽然我来晚了,但其他方法对我没有用,我不知道是因为我从远程源拉取了一个列表?

简而言之,有两个步骤:

  1. 获取所选项目的值
  2. 删除该项目

你显然可以让这段代码更小,但我留下了详细的阅读性

var $select = $('#users').selectize(); 
var selectSizeControl = $select[0].selectize; 
// 1. Get the value
var selectedValue = selectSizeControl.getValue()
// 2. Remove the option 
selectSizeControl.removeOption( selectedValue )

0
最近在实现这个功能时,如果删除最后一个项目,则输入看起来有点问题(如上所述)。一种解决方法(有点hackish)是在onItemRemove函数中查找保存的项目长度,如果length == 0,则使用jQuery修复输入 - $('.selectize-input').css({'height':'35px'});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接