jQuery UI Autocomplete Multiple Values in Textbox

前端 未结 2 1300
感动是毒
感动是毒 2020-12-30 12:58

I need a simple autocomplete search functionality but also allowing users to type more than one value. I\'m using jQuery UI\'s autocomplete widget (http://jqueryui.com/autoc

2条回答
  •  [愿得一人]
    2020-12-30 13:38

    To solve the issue of multiple strings in the same textbox AND include a regex to only show suggestions matching the start of the string I did the following:

        $('#search').autocomplete({
            minLength: 1,
            source: function (request, response) {
                var term = request.term;
    
                // substring of new string (only when a comma is in string)
                if (term.indexOf(', ') > 0) {
                    var index = term.lastIndexOf(', ');
                    term = term.substring(index + 2);
                }
    
                // regex to match string entered with start of suggestion strings
                var re = $.ui.autocomplete.escapeRegex(term);
                var matcher = new RegExp('^' + re, 'i');
                var regex_validated_array = $.grep(items, function (item, index) {
                    return matcher.test(item);
                });
    
                // pass array `regex_validated_array ` to the response and 
                // `extractLast()` which takes care of the comma separation
    
                response($.ui.autocomplete.filter(regex_validated_array, 
                     extractLast(term)));
            },
            focus: function () {
                return false;
            },
            select: function (event, ui) {
                var terms = split(this.value);
                terms.pop();
                terms.push(ui.item.value);
                terms.push('');
                this.value = terms.join(', ');
                return false;
            }
        });
    
        function split(val) {
            return val.split(/,\s*/);
        }
    
        function extractLast(term) {
            return split(term).pop();
        }
    

提交回复
热议问题