如何使Select2 4.0可排序?

时间:2016-02-22 19:18:24

标签: jquery jquery-select2-4 select2

我在新版本4.0中遇到了这个问题,并且无法找到任何答案,直到我自己解决了几个小时的工作后的解决方法。

2 个答案:

答案 0 :(得分:4)

我的解决方案解决方案:

首先,使用jquery对其进行排序。

$("#mySelect").parent().find("ul.select2-selection__rendered").sortable({
    containment: 'parent',
    update: function() {
        orderSortedValues();
    }
});

函数orderSortedValues具有以下想法: 更改原始选择输入选项的顺序,并通知select2新订单。

orderSortedPassageValues = function() {
    $("#mySelect").parent().find("ul.select2-selection__rendered").children("li[title]").each(function(i, obj){
        var element = $("#mySelect").children("option[value="+obj.title+"]");
        moveElementToEndOfParent(element)
    });
};

moveElementToEndOfParent = function(element) {
    var parent = element.parent();

    element.detach();

    parent.append(element);
};

最后,还需要通过下拉列表

选择新值来停止自动排序
stopAutomaticOrdering = function() {    
    $("#mySelect").on("select2:select", function (evt) {
        var id = evt.params.data.id;

        var element = $(this).children("option[value="+id+"]");

        moveElementToEndOfParent(element);

        $(this).trigger("change");
    });
}

PS:功能的范围是全局的。你可以改变它......希望能帮助别人。

答案 1 :(得分:0)

重新排列原始选择列表时,下拉菜单选项发生了更改。

所以我最终要做的是创建一个隐藏字段。

当选择更改时,此字段将更新。

<select class="select2field" name="FieldSelect" data-select2target="field-hiddenfield" multiple="">

  <option value="1">A</option>

  <option value="2">B</option>

  <option value="3">C</option>

</select>

<input type="hidden" name="FieldData" value="" class="hidden" id="field-hiddenfield">

然后,我更新了JS,以在发生排序或选择新项目时更新该字段。

var select2field = 'select.select2field';
$(select2field).select2({
  templateSelection: function (data, container) {
    // Add custom attributes to the <option> tag for the selected option
    var element = $(data.element);
    element.attr('data-content', element.html());
    return data.text;
  },
  closeOnSelect: false,
  multiple: true,
  placeholder: 'Select..',
  width: '100%'
});

var origSelect = $('#mySelect');
var select2Select = $("#mySelect").parent().find("ul.select2-selection__rendered");

function updateHiddenField() {
  var values = [];

  select2Select.children("li[title]").each(function(i, obj){

    values.push(origSelect.children("option[data-content='"+obj.title+"']").attr('value'));

  });

  // Update the hidden field.
  $('#' + origSelect.data('select2target')).val(values.join(','));
}

select2Select.sortable({
  containment: 'parent',
  update: function() {
    updateHiddenField();
  }
});

origSelect.on("select2:select", function (evt) {
  var id = evt.params.data.id;
  var element = $(this).children("option[value="+id+"]");
  element.detach();
  origSelect.append(element);
  $(this).trigger("change");

  updateHiddenField();
});