JQuery autocomplete multiple values

I am trying to implement jqueryui autocomplete for multiple values, but I am having problems. Parameters appear well when I start typing a name, but as soon as that name is selected, a comma is added to the list, and I no longer get the parameters as I type. The code I have is below.

function fillAutoComplete(friends_list) {
  $('input#opponents').autocomplete({
    minLength:0,
    source: $.map(friendList, function(item) {
      return {
    label: item.name,
    value: item.name,
    id: item.id
      }
    }),
    focus: function() {return false},
    multiple: true,
    select: function(event, ui) {
      var terms = (this.value).split(/,\s*/);
      terms.pop();
      terms.push(ui.item.value);
      terms.push("");
      this.value = terms.join(", ");
      var temp = $('input#oppID').val();
      if(temp != "") {
    $('input#oppID').val(temp + "," + ui.item.id);
      } else {
    $('input#oppID').val(ui.item.id);
      }
      return false; 
      }
    });
}

Thank.

+3
source share
1 answer

Recently, I had to do something very similar.

You need something like the following:

function fillAutoComplete(friends_list) {

$('input#opponents')
    .keydown(function(event) {
        var menuActive = $(this).data('autocomplete').menu.active;
        if (event.keyCode === $.ui.keyCode.TAB && menuActive)
            event.preventDefault();
    })
    .autocomplete({
        source: function(request, response) {
            // Apply filtering to list based on last term of input.
            var term = request.term.split(/[,;]\s*/).pop();
            if (!term) {
                response([]);
                return;
            }

            // Process list of friends.
            var list = $.map(friends_list, function(item) {
                return {
                    label: item.name,
                    value: item.name,
                    id: item.id
                }
            });

            // Apply filtering.
            list = $.grep(list, function(item) {
                return item.name.indexOf(term) === 0;
            });

            // Invoke jQuery callback.
            response(list);
        },
        focus: function() {
            var terms = this.value.split(/[,;]\s*/);
            terms.pop();
            terms.push( ui.item.value );
            this.value = terms.join(', ');
            return false;
        },
        select: function(event, ui) {
            var terms = this.value.split(/[,;]\s*/);
            terms.pop();
            terms.push(ui.item.value);
            terms.push('');
            this.value = terms.join(', ');
            return false;
        }
    });

}
+2
source

Source: https://habr.com/ru/post/1779070/


All Articles