如何从jQuery Select2元素中删除特定选项?

时间:2015-01-29 15:11:56

标签: jquery jquery-select2

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

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

我可以使用

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

Working demo is here

但无法取消选择按钮点击中的一个值。帮助我。

  • Priyank

1 个答案:

答案 0 :(得分: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中的truthy值。您应该检查集合的length

if ( selectTest.length > 0 )
//   ...
相关问题