Search code examples
javascriptsemantic-ui

Semantic UI multi-select dropdown prevent element selection


I am having a dropdown with 4 elements such as

'All', 'Fi', 'Cu', 'Common'. 

Here, user has to be allowed to select 'All' only when there is no element in it. If it has at least one element say 'Cu' in it & if user is selecting 'All' then the selection has to be prevented and 'All' will be removed from the dropdown.

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css"></script>

<div style="padding:10px;width:200px;">
    <select id="du_select" class="ui fluid dropdown" name="du_graph_types" multiple="">
        <option value="">Select DU</option>
        <option value="all">All</option>
        <option value="copper">Copper</option>
        <option value="fiber">Fiber</option>
        <option value="common">Common</option>
    </select>
</div>

<script type="text/javascript">
    $('#du_select').dropdown({
        onChange: function(value, text, $selectedItem) {
            // custom action
            if (value.length > 1 && value.includes('all')) {
                const index = value.indexOf('all');
                if (index > -1) {
                    value.splice(index, 1);
                }
                console.log('sel_items : ' + value)
                $('#du_select').dropdown('clear').dropdown('set selected',value)
                alert('Before selecting "All", clear the existing DU type')
            }

        }
    });

</script>

JSFiddle

But, while doing so, the elements are getting removed from the dropdown itself.

What is the mistake I'm making here ?


Solution

  • Your are using the wrong parameters in your logic. This solution should work.. simply change your onChange params.

    The dropdown onChange gives you: 1) array of all options that have been selected 2) currently selected value

    So you want to do this:

    $('#du_select').dropdown({
            onChange: function(selected, value) {
        console.log(value)
        console.log(selected)
                // custom action
                if (selected.length > 1 && selected.includes('all')) {
                    const index = selected.indexOf('all');
                    if (index > -1) {
                        selected.splice(index, 1);
                    }
                    console.log('sel_items : ' + selected)
                    $('#du_select').dropdown('clear').dropdown('set selected',value)
                    //$('#du_select').;
                    alert('Before selecting "All", clear the existing DU type')
                }
    
            }
        });
    

    Fiddle: https://jsfiddle.net/yumxj47v/