Autocomplete with Categories sorted

Viewed 234

I am implementing the jQuery UI Autocomplete based on the categories example in the documentation I need to sort (alphabetical order) the result by Autocomplete in Jquery, first in Categories (Hotel and Cities), then in the Itens (Names). Exemplo:

City

  • Miami
  • Orlando

Hotel

  • hotel A
  • hotel B

Any help starting me down the right path would be greatly appreciated.

$( function() {
    $.widget( "custom.catcomplete", $.ui.autocomplete, {
      _create: function() {
        this._super();
        this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
      },
      _renderMenu: function( ul, items ) {
        var that = this,
          currentCategory = "";
        $.each(items, function( index, item ) {
          var li;
            if (item.category != currentCategory) {
                ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
            currentCategory = item.category;
          }
          li = that._renderItemData( ul, item );
          if ( item.category ) {
            li.attr( "aria-label", item.category + " : " + item.label );
          }
        });
      }
    });
    var data = function (request, response) {
            $.ajax({
                type : 'GET',
                url: "http://commons.t4w.com.br/new/api/v1/mapping/autocomplete/all/"+ request.term +"/managerid/223/token/0b0f00da-30ec-4210-aca4-92aa6ea9470a",
                success: function (data) {
                    response($.map(data, function (item) {
                        if (item.type == "City" || item.type == "Hotel") {
                            var label = item.name["pt-BR"];
                            return {
                                label: label,
                                destinationId: item.destinationId,
                                category: item.type
                            }
                        }
                  }));
                }
              })
      };

    $( "#search" ).catcomplete({
        delay: 0,
        source: data,
        minLength: 3
    });
  } );
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
City:
<input id="search">

2 Answers

You can just use a function as the autocomplete source and then use $.get(), .filter() and .sort() to craft your autocomplete callback.

Other useful reading: template literals and spread operator.

let language = 'en'; //I assume you have a language selection somewhere

$( "#search" ).autocomplete({
  delay: 0,
  minLength: 3,
  select: function(e, ui) {
    //ui.item.data contains the object returned in the source callback
    //see beleow
    if (ui.item.data){
      //code to do stuff with the selection
    }
  },
  source: function (request, callback) {
    $.get(`http://commons.t4w.com.br/new/api/v1/mapping/autocomplete/all/${request.term}/managerid/223/token/0b0f00da-30ec-4210-aca4-92aa6ea9470a`)
      .done(function(suggestions) {
        if (suggestions) {
          //the data property set in the map function will be available in the select event
          //see above
          callback([
            { label: 'CITIES' }, //this is just a placeholder, it won't have a data property when selected
            ...suggestions
              .filter(item => item.type === 'City')
              .sort((a, b) => a.name[language].localeCompare(b.name[language]))
              .map(function (city) {
                return { label: city.name[language], data: city };
              }),
            { label: 'HOTELS' },
            ...suggestions
              .filter(item => item.type === 'Hotel')
              .sort((a, b) => a.name[language].localeCompare(b.name[language]))
              .map(function(hotel) {
                return { label: hotel.name[language], data: hotel };
              })
          ]);
        }
      })
      .fail(function(error) {
         //code to handle errors
      });
     }
  });
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
City:
<input id="search">

Thanks for the reply, it worked correctly. In this template, can I format the category name and items?

Related