How to dynamically filter a select2 listing based on option class

后端 未结 2 1894
时光说笑
时光说笑 2020-12-21 15:48

I have a dropdown select of optional \'opportunities\' (id=\"opportunities\" in the example below) which I enhance using the select2 jquery plugin, and wish to

2条回答
  •  死守一世寂寞
    2020-12-21 16:26

    ّshort Example .

    window.templateResult = function templateResult(state) {
                if (state.text.indexOf('ss') == -1)
                    return null;///hide
    
                if (!state.id) { return state.text; }
                var $state = $(
                  '' + state.text + ''
                );
                return $state;
            };
    
            //Init
            $("#select1").select2({
                templateResult: templateResult
            });
    

    ّFull Example below.

    $(document).ready(function () {
    
                //general custom filter
                window.Select2FilterFunc = function (state) { return "Default" };
    
                //general custom templateResult
                window.templateResult = function templateResult(state) {
    
                    //call custom filter
                    var result = Select2FilterFunc(state);
                    if (result != "Default")
                        return result;
    
                    if (!state.id) { return state.text; }
                    var $state = $(
                      '' + state.text + ''
                    );
                    return $state;
                };
    
                //Init
                $("#select1").select2({
                    templateResult: templateResult
                });
    
                //Add Custom Filter when  opening
                $('#select1').on('select2:opening', function (evt) {
    
                    //set your filter
                    window.Select2FilterFunc = function (state) {
                        if (state.text.indexOf('ss') == -1)
                            return null;//hide item
                        else
                            return "Default";
                    };
    
                }).on('select2:close', function (evt) {
                    window.Select2FilterFunc = function (state) { return "Default" };
                });
    
            });
    
    
    
    
    

提交回复
热议问题