Cross-browser search in select list

    Below we will talk about the drop-down list search method (select).

    This requires a text input field and the drop-down list itself:

    To make the search result more visible for the user, you should set the select tag with the size attribute with a value of 10.

    Add a little css to this :
    input, select {
        width: 300px;
        margin: 10px auto;
        display: block;
    }
    

    When entering data into the input field, everything that does not match the search string will be hidden, leaving only the desired results in the list.

    The list search is based on the use of regular expressions, and since the value in the input field is not constant, I use the object expression of regular expressions ( new RegExp () ) instead of literal:
    var field = $('#list').find('option');
    // собственно поиск
    $('#searchInput').bind('keyup', function() {
        var q = new RegExp($(this).val(), 'ig');
        for (var i = 0, l = field.length; i < l; i += 1) {
            var option = $(field[i]),
                parent = option.parent();
            if ($(field[i]).text().match(q)) {
                if (parent.is('span')) {
                    option.show();
                    parent.replaceWith(option);
                }
            } else {
                if (option.is('option') && (!parent.is('span'))) {
                    option.wrap('').hide();
                }
            }
        } 
    });
    

    It can be seen that the search itself is not difficult: all the interest in displaying the results found.
    The fact is that the simple application of properties hiding list items does not always lead to the expected result.
    For example, in some browsers ( Chrome , Internet Explorer ), if you simply add display: none to the option tag , the latter will still be visible.

    However, a simple feint with the ears of the same option tag wrapped in a span tag perfectly understands display: none , and behaves exactly as expected.

    PS: This method is neither valid nor semantic, however, it works fine in all browsers.

    An example .

    Also popular now: