Sort typeahead suggestions with the exact input at top

前端 未结 2 469
独厮守ぢ
独厮守ぢ 2021-02-05 23:10

I am using Twitter typeahead.js 0.10.5 as a suggestion engine. It works great, with one exception, I can\'t sort the list of suggestions the way I want.

As an example:

2条回答
  •  清歌不尽
    2021-02-06 00:02

    You want something along these lines. This will move the exact match to the top. You will want to continue modifying the sorter code to handle string case, whitespace, and how you want non perfect but close matches to be handled.This should get you started.

            var suggestion = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                local: data,
                limit: 20,
                sorter:function(a, b) { 
    
                         //get input text
                     var InputString=   $(Selector).val();
    
                         //move exact matches to top
                     if(InputString==a.value){ return -1;}
                     if(InputString==b.value){return 1;}
    
                          //close match without case matching
                     if(InputString.toLowerCase() ==a.value.toLowerCase()){ return -1;}
                     if(InputString.toLowerCase()==b.value.toLowerCase()){return 1;} 
    
                     if( (InputString!=a.value) && (InputString!=b.value)){
    
                          if (a.value < b.value) {
                             return -1;
                          }
                          else if (a.value > b.value) {
                             return 1;
                          }
                          else return 0;
                     }
                  },
              });
    

提交回复
热议问题