How to match multiple substrings in jQuery combobox autocomplete

Posted by John R on Stack Overflow See other posts from Stack Overflow or by John R
Published on 2012-09-21T20:30:21Z Indexed on 2012/09/25 15:37 UTC
Read the original article Hit count: 252

I found more than a couple examples of this with a plain jquery autocomplete but not in a way that will work with the autocomplete included in the combobox code from the demo because the structure of the code is structured so differently.

I want to match every item that has all of the search tokens anywhere in any word. I don't need to match the start of any word, any part of it is fine. I don't care if the search strings are highlighted in the autocomplete list if that makes things too complicated.

Desired search/result combos: (please excuse the spacing)
"fi th" "fi rst second th ird"
"rs on" "fi rs t sec on d third"
"ec rd" "first s ec ond thi rd"
but not limited to any max/min length or number of tokens.

EDIT

I figured part of it out using the code structure from the other autocorrect I had working.

source: function( requestObj, responseFunc ) {
    var matchArry = $("select > option").map(function(){return this.innerHTML;}).get();
    var srchTerms   = $.trim(requestObj.term).split(/\s+/);

    // For each search term, remove non-matches
    $.each (srchTerms, function (J, term) {
        var regX = new RegExp (term, "i");
        matchArry = $.map (matchArry, function (item) {
            if( regX.test(item) ){
                return{
                    label: item,
                    value: item,
                    option: HTMLOptionElement
                } ? item :null;
            }
        } );
    });

    // Return the match results
    responseFunc (matchArry);
},

and

select: function( event, ui ) {
    ui.item.option.selected = true;
    self._trigger( "selected", event, {
        item: ui.item.option
    });
    $("destination").val(ui.item.value);    // I added this line
},

but I can't get both multiple words AND being able to click to select working at the same time.

If I remove the } ? item :null; on the return in the map function I can click to select an item. If I leave it I can type multiple words, but I can't click any of the items...

Is that the problem or the option: this? I've tried replacing it with HTMLOptionElement and null and I'm stuck.

I am able to set the value of another field with ui.item.value within the select label but that doesn't put the value in the search box or close the dropdown menu.

Fiddle of current code: http://jsfiddle.net/eY3hM/

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery