【问题标题】:Select2: How to unselect all options and select only oneSelect2:如何取消选择所有选项并仅选择一个
【发布时间】:2012-11-01 09:05:38
【问题描述】:

我正在使用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']);"

但它似乎对我不起作用。

有什么线索吗?

【问题讨论】:

    标签: jquery jquery-select2


    【解决方案1】:

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

    $('#selectId').select2('val',"");
    

    【讨论】:

      【解决方案2】:

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

      fiddle here

      它基于点击事件。

      $(function() {
          $('#fruits').click(function(e) {
              var selected = $(e.target).val();
              if(selected=='all'){
                 $('#fruits > option').prop("selected",false);
                 $(e.target).prop("selected",true);
              };
          }); 
      });
      

      【讨论】:

      • 如果您分享您的工作解决方案,它会让包括我在内的其他人高兴...接受的答案中的那个肯定不起作用。
      • 你能告诉我什么对你不起作用......我猜 OP 得到了他想要的东西......如果你选择所有其他的东西,如果你签入小提琴,其他所有东西都将被取消选择
      【解决方案3】:

      使用这个:

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

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

      2)全选

       $('#fruits option:[text="All"]').attr('selected', true);
      

      【讨论】:

        【解决方案4】:

        试试这个

         $("#fruits option:selected").removeAttr("selected");
        
         $("#fruits option[value='']").attr("selected","selected");
        

        【讨论】:

          猜你喜欢
          • 2013-09-17
          • 2013-05-08
          • 1970-01-01
          • 2019-01-05
          • 1970-01-01
          • 2018-05-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多