Select2: Limiting the number of selections in one optiongroup ?

Created on 19 Sep 2016  路  3Comments  路  Source: select2/select2

Hello,

Your plugin works very well but I have a question about option groups : is it possible to limit the number of selections in each group ?

For example, I have a multiple select :

<select class="select2" [...]>
    <optgroup label="Color">
        <option value="black">Black</option>
        <option value="blue">Blue</option>
        <option value="white">White</option>
    </optgroup>
    <optgroup label="Size">
        <option value="size-s">S</option>
        <option value="size-m">M</option>
        <option value="size-l">L</option>
        <option value="size-xl">XL</option>
    </optgroup>
</select>

I would like the user selects only one color and one size.
Even if the plugin doesn't cover this way of selecting options, maybe you have an idea to do this in jQuery or native JS ?

Thank you.

Most helpful comment

Hey, @lk77, I don't know if there is a better way to do this, but I could get the element that triggered the event using: e.params.args.data.element

Here is how I implemented 1 option per optgroup

var $tag = $("#receivers");

$tag.on('select2:selecting', function(e) {
  var sibling_elements = e.params.args.data.element.parentElement.children
  for(var i = 0; i < sibling_elements.length; i++) {
    sibling_elements[i].selected = false
  }
});

I will like to know if there is a better way to do this.
I also want to implement validating the selection of 1 option from each group.

All 3 comments

Hello,

there is a solution for this?

i need to have a maximum of 1 option selected by optgroup,
i tried the select2:selecting event to deselect the previously selected element in the optgroup, but i can't retrieve de option element that triggered the event.

if you have some clues, thanks.

Hey, @lk77, I don't know if there is a better way to do this, but I could get the element that triggered the event using: e.params.args.data.element

Here is how I implemented 1 option per optgroup

var $tag = $("#receivers");

$tag.on('select2:selecting', function(e) {
  var sibling_elements = e.params.args.data.element.parentElement.children
  for(var i = 0; i < sibling_elements.length; i++) {
    sibling_elements[i].selected = false
  }
});

I will like to know if there is a better way to do this.
I also want to implement validating the selection of 1 option from each group.

This appears to be a usage question, rather than a bug report or feature request. Please see our contributing guidelines.

Usage questions should be discussed on the forums instead.

Was this page helpful?
0 / 5 - 0 ratings