How to suggest similar words in autocomplete

后端 未结 2 1156
情书的邮戳
情书的邮戳 2021-01-03 12:03

I have an input field for locations with jquery-ui-autocomplete.



        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 12:40

    You are almost there. You can use the response function (see in API) to remove the alternate spellings from the results. Also put the best spelling ("Mallorca" in this case) last. Check this out, I hope the comments are enough to get the logic. Try to type "Ma", or "Maj" and select the only option. In both cases it will display "Mallorca"

     $( function() {
        var availableTags = [      
        { value: 'Mallorca', label: 'Palma de Mallorca' },
        { value: 'Mallorca', label: 'Majorca' },
        { value: 'Mallorca', label: 'Mallorca' },
        { value: 'Madrid', label: 'Madrid' }
        ];
        $( "#tags" ).autocomplete({
          source: availableTags,      
          response: function( event, ui ) {
            var added = [];//Keep here the unique labels that are already in the list
            for(var i=ui.content.length-1;i>=0;i--){//Start a loop, itterate all items backwards
              var cur = ui.content[i].value;//Value of the item
              if($.inArray(cur,added)==-1){//If not already loaded
                added.push(cur);//Put the new item in the list
              }else{            
                ui.content.splice(i,1);//If already loaded remove it from the results
              }
            }        
          }
        });
      } );
    
    
    
    

提交回复
热议问题