使用select2可选择的optgroup

时间:2014-11-17 03:07:39

标签: jquery html jquery-select2

我使用select2从下拉列表中选择多个选项,但是select2可以选择完整的optgroup吗?我想要的是当用户选择选项组时,应选择所有子选项。我想用jQuery Select2来做这件事。我怎么能这样做?

7 个答案:

答案 0 :(得分:19)

如果您使用隐藏的输入元素(而不是选择元素)支持Select2,则可以这样做。

要使组选项可选,您必须为其指定“id”,但它似乎可以是空字符串。然后,您可以使用“select2-selecting”事件来阻止选择组选项,而是选择其子选项。

此外,可以提供query功能,以防止在选择了所有子选项后,组选项出现在列表中。

如果你有这样定义的选项:

var FRUIT_GROUPS = [
    {
        id: '',
        text: 'Citrus',
        children: [
            { id: 'c1', text: 'Grapefruit' },
            { id: 'c2', text: 'Orange' },
            { id: 'c3', text: 'Lemon' },
            { id: 'c4', text: 'Lime' }
        ]
    },
    {
        id: '',
        text: 'Other',
        children: [
            { id: 'o1', text: 'Apple' },
            { id: 'o2', text: 'Mango' },
            { id: 'o3', text: 'Banana' }
        ]
    }
];

您可以像这样检测Select2:

$('#fruitSelect').select2({
    multiple: true,
    placeholder: "Select fruits...",
    data: FRUIT_GROUPS,
    query: function(options) {
        var selectedIds = options.element.select2('val');
        var selectableGroups = $.map(this.data, function(group) {
            var areChildrenAllSelected = true;
            $.each(group.children, function(i, child) {
                if (selectedIds.indexOf(child.id) < 0) {
                    areChildrenAllSelected = false;
                    return false; // Short-circuit $.each()
                }
            });
            return !areChildrenAllSelected ? group : null;
        });
        options.callback({ results: selectableGroups });
    }
}).on('select2-selecting', function(e) {
    var $select = $(this);
    if (e.val == '') { // Assume only groups have an empty id
        e.preventDefault();
        $select.select2('data', $select.select2('data').concat(e.choice.children));
        $select.select2('close');
    }
});

jsfiddle

以下是没有query功能的jsfiddle,其中当选择了所有子选项时,组选项仍会显示。

答案 1 :(得分:2)

首先为您的选择提供ID 例如

<select style="width: 95%" id="selectgroup">

然后将类添加到您的optgroup,如

 <optgroup value="ATZ" label="Alaskan/Hawaiian Time Zone" class="select2-result-selectable">

然后添加此

$('#selectgroup').select2({

    }).on('select2-selecting', function (e) {
        debugger;
        var $select = $(this);
        if (e.val == undefined) {
            e.preventDefault();
            var childIds = $.map(e.choice.children, function (child) {
                return child.id;
            });
            $select.select2('val', $select.select2('val').concat(childIds));
            $select.select2('close');
       }
    });

如果您点击optgroup,那么它将选择optgroup下的所有选项。

答案 2 :(得分:1)

在Select2 v4中,我发现John S的答案不起作用(see here)。我使用AJAX将数据作为数组加载并创建了一个解决方法:

$(document).on("click", ".select2-results__group", function(){
    var input = $(this);
    var location = input.html();
    // Find the items with this location
    var options = $('#select2 option');
    $.each(options, function(key, value){
        var name = $(value).html();
        // The option contains the location, so mark it as selected
        if(name.indexOf(location) >= 0){
            $(value).prop("selected","selected");
        }
    });
    $("#select2").trigger("change");
});

我按位置对项目进行分组,每个选项都包含位于其中的位置名称html。每次点击optgroup标题时,我都会得到它的位置(下拉列表中显示的名称)。然后我查看#select2表中的所有选项,并在其html中查找哪些选项包含该位置。

我知道这是一个hacky解决方法,但希望它有助于/指出正确的方向。

答案 3 :(得分:0)

John S,提供的示例在大多数情况下工作得非常好(对于V3)。但它有一个错误:

假设选择列表足够长以便滚动。当您选择任何组中仅在向下滚动后可用的任何项目时 - 您不能再选择从该组中选择的项目之后的下一个项目。这是因为select2的ensureHighlightVisible方法开始行为不端,因为它使用的选择器使用的假设组始终是“不可选择的”。因此,每次尝试选择项目时,滚动都会跳转。

所以不幸的是,虽然这个解决方案看起来非常好 - 我放弃它并重新实现它而不使用组ID:

$selectEl..on("select2-open", function(event) {
          $(event.target).data("select2").dropdown.on("click", "li.select2-result-unselectable", selectGroup);
          $(event.target).data("select2").dropdown.on("mousemove-filtered", "li.select2-result-unselectable", highlight);
        }).on("select2-close", function(event) {
          $(event.target).data("select2").dropdown.off("click", "li.select2-result-unselectable", selectGroup);
          $(event.target).data("select2").dropdown.off("mousemove-filtered", "li.select2-result-unselectable", highlight);
        });

  // selection of the group.
  function selectGroup(e) {
    var $li = $(this);
    e.preventDefault();
    $select.select2('data', $select.select2('data').concat($li.data("select2Data").children));
    $select.select2('close');
    _this.$field.trigger('change');
  }

  // highlight of the group.
  function highlight(e) {
    if ($(e.target).hasClass("select2-result-unselectable") || $(e.target.parentNode).hasClass('select2-result-unselectable')) {
      e.preventDefault();
      e.stopPropagation();
      $select.data("select2").dropdown.find(".select2-highlighted").removeClass("select2-highlighted");
      $(this).addClass("select2-highlighted");
    }
  }

答案 4 :(得分:0)

好吧,我遇到了这个问题,我发现每次select2(Select2 4.0.5)打开时,它会在关闭的body元素之前添加一个span元素。另外,在span元素中添加一个带有id:select2-X-results的ul,其中X是select2 id。 所以我找到了以下解决方法(jsfiddle):

var countries = [{
  "id": 1,
  "text": "Greece",
  "children": [{
    "id": "Athens",
    "text": "Athens"
  }, {
    "id": "Thessalonica",
    "text": "Thessalonica"
  }]
}, {
  "id": 2,
  "text": "Italy",
  "children": [{
    "id": "Milan",
    "text": "Milan"
  }, {
    "id": "Rome",
    "text": "Rome"
  }]
}];

$('#selectcountry').select2({
  placeholder: "Please select cities",
  allowClear: true,
  width: '100%',
  data: countries
});

$('#selectcountry').on('select2:open', function(e) {

  $('#select2-selectcountry-results').on('click', function(event) {

    event.stopPropagation();
    var data = $(event.target).html();
    var selectedOptionGroup = data.toString().trim();

    var groupchildren = [];

    for (var i = 0; i < countries.length; i++) {


      if (selectedOptionGroup.toString() === countries[i].text.toString()) {

        for (var j = 0; j < countries[i].children.length; j++) {

          groupchildren.push(countries[i].children[j].id);

        }

      }


    }


    var options = [];

    options = $('#selectcountry').val();

    if (options === null || options === '') {

      options = [];

    }

    for (var i = 0; i < groupchildren.length; i++) {

      var count = 0;

      for (var j = 0; j < options.length; j++) {

        if (options[j].toString() === groupchildren[i].toString()) {

          count++;
          break;

        }

      }

      if (count === 0) {
        options.push(groupchildren[i].toString());
      }
    }

    $('#selectcountry').val(options);
    $('#selectcountry').trigger('change'); // Notify any JS components that the value changed
    $('#selectcountry').select2('close');    

  });
});
li.select2-results__option strong.select2-results__group:hover {
  background-color: #ddd;
  cursor: pointer;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>


<h1>Selectable optgroup using select2</h1>
<select id="selectcountry" name="country[]" class="form-control" multiple style="width: 100%"></select>

答案 5 :(得分:0)

我找到了Select2 v4插件,它增加了单击optgroup来选择/取消选择所有子选项的功能。它对我来说非常有效。 bnjmnhndrsn/select2-optgroup-select

感谢本·亨德森!

答案 6 :(得分:0)

使用选择元素的V 4.0.2的一个选项:

<select style="width:100%;" id="source" multiple="" tabindex="-1" aria-hidden="true">                 
   <optgroup class="select2-result-selectable" label="Statuses"   >        
      <option value="1">Received</option>                          
      <option value="2">Pending Acceptance</option>                             
   </optgroup>                                 
   <optgroup class="select2-result-selectable" label="Progress" >                
      <option value="6">In Progress</option>
      <option value="7">Follow Up</option>                         
  </optgroup>                                                    
</select>

JS + jQuery:

$(document).ready(function() {

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

$(document).on("click", ".select2-results__group", function(){

    var groupName = $(this).html()
    var options = $('#source option');

    $.each(options, function(key, value){

        if($(value)[0].parentElement.label.indexOf(groupName) >= 0){
            $(value).prop("selected","selected");
        }

    });

    $("#source").trigger("change");
    $("#source").select2('close'); 

  });
});

提琴:https://jsfiddle.net/un1oL8w0/4/

相关问题