Make a long HTML select for better usability

155 views Asked by At

In a HTML select, I've 10 optgroup and each optgroup has 30 items, so there are 300s option in a select...it is a huge list.

Is it possible to use some CSS or JS library so the options under each optgroup will be displayed only when current optgroup is selected?

Something like the 2 level JS menu but I am using a HTML select as the source. Is it possible?

1

There are 1 answers

2
Jose Rey On

Yes, it should be possible to populate a select box in that way.

The trick would be to know when a values are for the first level, and when they are just refill the select. Then onchange event should be doing something like:

function selChange(sel) {
    var optVal = sel.val();
    if (isFirstLevel(optVal)) {
        fill_options("#select", optVal)
    }
}

In case of an ajax call to the backend fill_options could be something like:

function fill_options(selectId, optVal) {
    $.ajax({
        type: "POST",
        url: 'http://example.com/ajax_refill',
        data: {'category': optVal },
        dataType:'json',
        success: function(data) {

           var select = $(selectId), options = '';
           select.empty();      

           for(var i=0;i<data.length; i++)
           {
            options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";              
           }

           select.append(options);
        }
    });
}

The function isFirstLevel() ideally depends on the structure (syntax) of the values so a simple operation like a regex will do, but it can be arbitrarily complex, doing ajax calls and any other stuff needed.

But the user interface of such box may be confusing to the user, having two select boxes may be more intuitive solution for the users.