1

我正在使用Select2,一个很棒的插件。

HTML:

<select id="fruits" multiple="true">
  <option value=''>All
  <option value='Apple'>Apple
  <option value='Pear'>Pear
  ...

JavaScript:

$('#fruits').select2();

当我选择“全部”选项时,我需要取消选择所有以前选择的选项,只选择“全部”选项。

我试过了

onChange="$('#fruits').select2('val', ['All']);"

onChange="$('#fruits').select2('data', ['All']);"

但这似乎对我不起作用。

有什么线索吗?

4

4 回答 4

4

这是对的。这段代码对我很有效。

$('#selectId').select2('val',"");
于 2016-05-03T11:11:00.593 回答
2

我用我的代码添加了这个小提琴,试试这个......

在这里摆弄

它基于点击事件。

$(function() {
    $('#fruits').click(function(e) {
        var selected = $(e.target).val();
        if(selected=='all'){
           $('#fruits > option').prop("selected",false);
           $(e.target).prop("selected",true);
        };
    }); 
});
于 2012-11-01T09:19:14.627 回答
1

用这个:

1)用于取消选择的项目。

$("#fruits option:selected").removeAttr("selected");

2)用于全选

 $('#fruits option:[text="All"]').attr('selected', true);
于 2012-11-01T09:19:53.797 回答
0

试试这个

 $("#fruits option:selected").removeAttr("selected");

 $("#fruits option[value='']").attr("selected","selected");
于 2012-11-01T09:17:40.540 回答