Topic: Select all in optgroup

parson premium asked 2 years ago


Is it possible to have 'select all' options but for optgroups in a select?

E.g.

<select class="select">
  <optgroup label="Group 1">
        <option value="1">Select all group 1</option>
        <option value="2">Option1</option>
        <option value="3">Option2</option>
        <option value="4">Option3</option>
        <option value="5">Option4</option>
    </optgroup>
    <optgroup label="Group 2">
        <option value="6">Select all group 2</option>
        <option value="7">Option5</option>
        <option value="8">Option6</option>
        <option value="9">Option7</option>
        <option value="10">Option8</option>
    </optgroup>
</select>

So if 'Select all group 1' is ticked Option1, Option2, Option3 and Option4 are selected. I know I can add an event listener which will listen for a value change and can set values there. However, this closes the select dropdown. I want to replicate the same behavior as the current 'Select All' and have the dropdown stay open to show the selections.


parson premium answered 2 years ago


I've solved this problem. I get the select as an instance and have an event listener for optionSelect and optionDeselect that passes e in as a variable. In each listener I check to see if the select group option has been selected/deselected and then feed the options I would like selected/deselected as an array into the following code (this is the deselect function):

function deselectOptions(options) {
        options.forEach((option) => {
            if (option.selected && !option.disabled) {
                mySelect._selectionModel.deselect(option)
                option.deselect()
            }
        })
        mySelect._updateInputValue()
        mySelect._updateLabelPosition()
        mySelect._updateClearButtonVisibility()
        mySelect._emitValueChangeEvent(e.value)
    }

I found the functions I needed after looking through your Javascript source code.


parson premium answered 2 years ago


Hi,

I'm aware that this isn't an option. I'm quite happy to write my own code for this. If I set the selected options manually using setValue() it closes the dropdown. I would like to replicate the way the 'select all' option works, ticking a set of boxes and keeping the dropdown open.

What I would like is a steer on how you implement the 'select all' function so I can replicate it for a limited set of options.


Michał Duszak staff answered 2 years ago


Hello, MDB doesn't provide such an option.



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Premium
  • Premium support: Yes
  • Technology: MDB Standard
  • MDB Version: MDB5 3.9.0
  • Device: PC
  • Browser: Chrome
  • OS: Windows 10
  • Provided sample code: No
  • Provided link: No