Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 optgroup inside optgroup

Is it possible to have multiple layers of optgroup on select2?
Basically, an optgroup inside another optgroup.

<select>
    <optgroup label="Level_1">
        <optgroup label="Level_2">
            <option value="option_1">option_1</option>
            <option value="option_2">option_2</option>
        </optgroup>
    </optgroup>
</select>

Fiddle

Thank you.

like image 552
Manatax Avatar asked Sep 07 '25 08:09

Manatax


2 Answers

Nested optgroups are not supported in html, But you can use JavaScript to create them.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script>
            $(document).ready(function () {
                $('#NestedOptGroups').select2({
                    data: [
                        {
                            text: 'Level_1', children: [
                            {
                                text: 'Level_2', children: [
                                {id: 'Level2Opt0', text: 'Sub Option 1'},
                                {id: 'Level2Opt1', text: 'Sub Option 2'}
                            ]
                            },
                            {id: 'Level1Opt0', text: 'Main Level option 1'}
                        ]
                        }
                    ]
                });
            });
        </script>

    </head>
    <body>
            <input class="select2" id="NestedOptGroups" placeholder="select one"/>
    </body>
</html>
like image 97
mmv_sat Avatar answered Sep 11 '25 01:09

mmv_sat


Try like this:

<select>
    <optgroup label="Level_1">
        <optgroup label="&nbsp;&nbsp;&nbsp;&nbsp;Level_2">
            <option value="option_1">&nbsp;&nbsp;&nbsp;&nbsp;option_1</option>
            <option value="option_2">&nbsp;&nbsp;&nbsp;&nbsp;option_2</option>
        </optgroup>
    </optgroup>
</select>

Check this Demo

like image 22
King_Fisher Avatar answered Sep 11 '25 01:09

King_Fisher