【问题标题】:How do I remove a particular option from a jQuery Select2 element?如何从 jQuery Select2 元素中删除特定选项?
【发布时间】:2015-03-28 20:58:20
【问题描述】:

我正在使用 jQuery Select2(版本 4)。

我正在使用选择标签以及允许多选的选项。

我可以使用

清除选定的选项
 selectTest.val(null).trigger('change');

Working demo is here

但无法在单击按钮时仅取消选择其中一个值。帮帮我。

  • 普里扬克

【问题讨论】:

  • 是什么让这个选项“特别”?
  • 就像有 4 个选项(1、2、3、4)。用户选择了 1 和 2。现在我想在单击按钮时从选择中删除 1。按钮由我提供。
  • 非常适合我。我可以单击已选择的选项并将它们删除
  • 你在什么浏览器中尝试这个?它也适合我
  • 他想以编程方式删除一个选项。获取选定的选项(一个数组),删除选项,然后重置值。该库似乎没有用于删除选项的 API。

标签: jquery jquery-select2


【解决方案1】:

如果您想以编程方式取消选择一个选项,您可以选择目标选项并将其selected 属性设置为false

$('#btn-clear').on('click', function () {
    var value = '2';
    // find the target option
    // if you want to deselect more that 1 option
    // you can use an array and jQuery `$.inArray` methiod, i.e.:
    // return $.inArray(this.value, values) > -1;
    selectTest.children().filter(function() {
       return this.value == value;
    }).prop('selected', false);
    // trigger the change event so the library recreates the tags
    selectTest.change();
});

我有updated the fiddle

请注意,if(selectTest){ 始终为 true。 jQuery 构造函数返回一个对象,一个对象是 JavaScript 中的真值。您应该检查集合的length

if ( selectTest.length > 0 )
//   ...

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2012-02-07
    • 1970-01-01
    相关资源
    最近更新 更多