Mhluzi Bhaka
Mhluzi Bhaka

Reputation: 1392

Autocomplete to return main word for group of words

I am using jQuery autocomplete - https://jqueryui.com/autocomplete/ and have this working for a dropdown:

$(function() {
    var availableTags = [
        "ActionScript",
        "Asp",
        "BASIC",
        "C",
        "ColdFusion",
        "Scheme"
    ];

    $( "#tags" ).autocomplete({
        source: availableTags
    });
});

Now I would like to have another scenario where if users start typing the words in a "related array" then they will get prompted to select the main word.

So using the below as examples:

Small Businesses    
    retailers; merchants; traders; wholesalers; vendor; 

Postal Service/Courier  
    parcel; package; post; postal service; delivery; courier; shipment; carting; dispatch

Business community  
    commerce; trade, career 

So if a user starts typing r..e..t.. and so on for retailers they would then get the main word/phrase being "Small Businesses"

I thought this could be done using optgroups perhaps but am not sure if it is possible at all and if so how to go about doing it. I need something that would kind of be how optgroups work but in reverse.

Any ideas would be great!

Upvotes: 0

Views: 55

Answers (1)

blgt
blgt

Reputation: 8205

If you can make the source array contain objects with label/value pairs, you can then allow the values to be arrays and parse them in a custom function for the source option. For example:

$( "#tags" ).autocomplete({
    source: function(request,response) {
        var responseItems = [], matches = false;
        for(var i in availableTags) {
            var tag = availableTags[i];
            if ($.isArray(tag.value)) {
                tag.value.forEach(function(val) {
                    matches |= val.indexOf(request.term) !== -1;
                });
            }
            else {
                matches = tag.value.indexOf(request.term) !== -1;
            }

            if (matches) {
                responseItems.push(tag.label);
            }
        }
        response(responseItems);
    }
});

Here's the above in a working fiddle: http://jsfiddle.net/6osjwgpt/

Upvotes: 1

Related Questions