SchweizerSchoggi SchweizerSchoggi - 5 months ago 32
jQuery Question

jQuery Autocomplete to find exact match

I hav a jQuery Autocomplete for airports. My dataset contains label and value.
Sample:

var Airports = [
{ "label": "DMB - Dzhambyl, Dzhambyl Airport", "value": "DMB" },
{ "label": "EMA - Nottingham, Nottingham East Midlands Airport", "value": "EMA" },
{ "label": "HAM - Hamburg, Hamburg Airport", "value": "HAM" }
];


When I enter HAM (which is the 3LC for Hamburg Airport) I currently get all of these three items as a result. But I only want to see "HAM - Hamburg, Hamburg Airport" if the value of this item matches the exact search request. It should also be possible to find all entries with e.g. "burg" in it if I would search for that.

Demo: https://jsfiddle.net/SchweizerSchoggi/pguoa197/1/

Answer

Don't know who voted this question down and why... but here is the solution for who ever will need something similar in the future:

$(function () {
    var Airports = [
        { "label": "DMB - Dzhambyl, Dzhambyl Airport", "value": "DMB" }, 
        { "label": "EMA - Nottingham, Nottingham East Midlands Airport", "value": "EMA" }, 
        { "label": "HAM - Hamburg, Hamburg Airport", "value": "HAM" }    
    ];


$("#depart").autocomplete({
     source: function (request, response) {
        var term = $.ui.autocomplete.escapeRegex(request.term)
            , startsWithMatcher = new RegExp("^" + term, "i")
            , startsWith = $.grep(Airports, function(value) {
                return startsWithMatcher.test(value.label || value.value || value);
            })
            , containsMatcher = new RegExp(term, "i")
            , contains = $.grep(Airports, function (value) {
                return $.inArray(value, startsWith) < 0 && 
                    containsMatcher.test(value.label || value.value || value);
            });

            response(startsWith.concat(contains));
    },
    minLength: 3
  });
});

Working Sample: https://jsfiddle.net/SchweizerSchoggi/pguoa197/5/

Comments