简体   繁体   中英

jQuery autocomplete: downsize list on value input field

How can I filter the list when 1 of the parameters is given (in a different field than the search field). For example, the user specifies the group ="Test" and start searching in the #ContactPerson field. I want only the records where "group":"Test" showing up.

   ("#ContactPerson").autocomplete({
              source: [{"value":"XYZ","name":"ZJL","group":"Test"},...]
    ...

This is what I've tried so far, but it does not work: http://jsfiddle.net/71puvk59/

according to this answer you can override the search function and apply all your filters.

In your case:

 var source = [
    {"value": "JL", "name": "JL", "group": "Test"},
    {"value": "MV", "name": "MV", "group": "Family"}
];

$('#ContactPerson').autocomplete({
    source: source,
    search: function (oEvent, oUi) {
        // get current input value
        var sValue = $(oEvent.target).val();

        //groupValue
        var groupValue = $("#group").val();

        // init new search array
        var aSearch = [];

        // for each element in the source array ...
        $(source).each(function (iIndex, sElement) {

            var groupFilterMatch = ((groupValue && sElement.group.indexOf(groupValue) != -1) || !groupValue);
            var nameFilterMatch = sElement.name.indexOf(sValue) != -1;

            // ... APPLY YOUR FILTERS HERE
            //Example: filter group, if it is defined, and filter name
            if (groupFilterMatch && nameFilterMatch) {
                // add element
                aSearch.push(sElement);
            }
        });

        // change search array
        $(this).autocomplete('option', 'source', aSearch);
    }
});

http://jsfiddle.net/vcarvalho/91Lj5nxx/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM