问题
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