Jquery: Filter dropdown list as you type

前端 未结 8 1759
粉色の甜心
粉色の甜心 2020-12-04 09:46

I have used a prototype plugin which filters the contents of a dropdown as you type. So for example if you typed \'cat\' into the text box, only items containing the substri

相关标签:
8条回答
  • 2020-12-04 10:00

    I just implemented this feature quick and dirty. It uses some global variables, you might want to improve the implementation to remove these.

    Here the '#xsca_member_filter' is the filter as a text input and '#members' is the select input.

    $('documenet').ready(function(){
        init();
       $('#xsca_member_filter').keyup(function(){
           filter($(this));
       });
    });
    
    //save all available options with their values and the empty option.
    init = function(){
        options = new Object();
        $('#owner option').each(function(){
            var obj = $(this);
            if(obj.attr("value") != "")
                options[obj.attr('value')] = obj.html();
            else
                emptyOption = obj.html();
        });
        selObj = $('#owner');
    };
    
    filter = function(elem){
        var filter = elem.val();
        var selected = $('#owner option:selected').val();
    
        //delete all options and add the empty option
        selObj.html("");
        selObj.append("<option> "+emptyOption+" </option>");
    
        //add all options conaining the filter string
        for(value in options){
            var option = options[value];
            if((options[value]).indexOf(filter) != -1){
                selObj.append("<option value='"+value+"'> "+options[value]+" </option>");
            }
        }
    
        //select the previously selected option
        $("#owner option[value = '"+selected+"']").prop("selected", true);
    }
    
    0 讨论(0)
  • 2020-12-04 10:04

    Select2 is a fairly recent fork of Chosen and has tons more features (e.g. AJAX + custom HTML for individual items).

    0 讨论(0)
提交回复
热议问题