Limit select2 selections by group?

江枫思渺然 提交于 2019-12-23 20:50:38

问题


Has anyone come up with a way to limit select2's selection by group?

I'm hoping to auto-remove any selection from the same group once something from that group is selected (effectively limiting to one selection per group)

I'll be working on something and will post it here if nobody posts a good solution before I'm finished.


回答1:


It is possible to prevent selections from being made in Select2, so this can be done depending on how "group" is defined. If a "group" is an <optgroup> in a standard <select>, it's just a matter of checking to see if any other options in the <optgroup> have been selected, and prevent the in-progress selection based on that.

Select2 emits a select2:selecting event when a selection is being made, and this event can be prevented by calling preventDefault() on it.

$("#mySelect").on("select2:selecting", function (evt) {
  var data = evt.params.data;
  var $element = $(data.element);

  // check if any options in the group are selected
  if ($element.parent("optgroup").find(":selected").length) {
    evt.preventDefault();
  }
});



回答2:


Kevin Brown's answer was very close to what I was looking for, but I actually wanted to auto-deselect any selected options from the same optgroup. I got it working with the following:

$("#my-select").on("select2-selecting", function (event) {
    $(event.object.element).parent("optgroup").find(":selected").attr('selected', false);
    $("#my-select").trigger('change');
});

NOTE: I'm using Select2 3.5.2



来源:https://stackoverflow.com/questions/30246868/limit-select2-selections-by-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!