JQueryUI Autocomplete - multiple values, remote

August 16, 2017

This is an example of an autocomplete field which allows to enter several values on an input box.

The list of suggested values on the pull down are retrieved from a remote script. In this example a php script.


<html>
<head>
  <meta charset="utf-8" />

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <style>
  .ui-autocomplete-loading {
    background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>
<body>

  <div>
    <label for="items">Items: </label>
    <input id="items" name="items" value="" />
  </div>

  <script>
  $(function() {

    $("#items")
    // don't navigate away from the field on tab when selecting an item
    .on("keydown", function(event) {
      if (event.keyCode === $.ui.keyCode.TAB &&
        $(this).autocomplete("instance").menu.active) {
        event.preventDefault();
      }
    })
    .autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "jquery_autocomplete_search.php",
          dataType: "json",
          data: {
            search_text: request.term.split(/,\s*/).pop(),
            max_rows: 12,
          },
          success: function(data) {
            response(data);
          }
        });
      },
      minLength: 2,
      focus: function() {
        // prevent value inserted on focus
        return false;
      },
      select: function(event, ui) {
        var terms = this.value.split(/,\s*/);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        this.value = terms.join(", ");
        return false;
      },
      open: function(event, ui) {
        // when used on a bootstrap's modal dialog, the autocomplete drop-down appears behind the modal.
        // this put it back on top
        $("ul.ui-autocomplete").css("z-index", 5000);
      }
    });

  });
  </script>

</body>
</html>

The php script must return an array in json format as shown in the following code.



Code based on https://jqueryui.com/autocomplete/#multiple-remote