JSFiddle - React, Tailwind, and code Playground

by Valentin Sarychev

HTML

<div id="selectGroup"></div>

CSS

select {
    margin: 5px 0;
    border-radius: 7px;
    background: #5a5772;
    color:#fff;
    border:none;
    outline:none;
    cursor:pointer;
    width: 203px;
    height: 50px;
    box-sizing: border-box;
    display: block;
}

JavaScript

var myList = [{
    value: 'A',
    title: 'Value A',
    children: [{
        value: 'a',
        title: 'Small value A',
        children: [
            { value: '1', title: 'Value 1' },
            { value: '2', title: 'Value 2' },
            { value: '3', title: 'Value 3' }
        ]
    },{
        value: 'b',
        title: 'Small value B',
        children: [
            { value: '4', title: 'Value 4' },
            { value: '5', title: 'Value 5' },
            { value: '6', title: 'Value 6' }
        ]
    }]
},{
    value: 'B',
    title: 'Value B',
    children: [{
        value: 'c',
        title: 'Small value C',
        children: [
            { value: '7', title: 'Value 7' },
            { value: '8', title: 'Value 8' },
            { value: '9', title: 'Value 9' }
        ]
    },{
        value: 'd',
        title: 'Small value D',
        children: [
            { value: '10', title: 'Value 10' },
            { value: '11', title: 'Value 11' },
            { value: '12', title: 'Value 12' }
        ]
    }]
}];

function createSelect($parent, list) {
    var $select = $('<select>');
    
    if ($parent.is('select')) {
        $select.insertAfter($parent);
    } else {
        $select.appendTo($parent);
    }
    
    $.each(list, function() {
        $('<option>')
            .data('children', this.children)
            .attr('value', this.value)
            .text(this.title || this.value)
            .appendTo($select);
    });
    
    $select.on('change', function() {
        var $self = $(this);
        var childList = $self.children('option:selected').data('children');
        $self.nextAll().remove();
        if (!childList) return;
        createSelect($self, childList);
    });
    
    $select.trigger('change');
}

function addNone(list) {
    list.unshift({ value: '-' });
    $.each(list, function() {
        if (!this.children) return;
        addNone(this.children);
    });
}

addNone(myList);

createSelect($('#selectGroup'), myList);