jQuery UI Autocomplete - Multiple values using Textarea

by Twisty

HTML

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
  <label for="tags">Tag programming languages: </label>
  <textarea id="tags" size="50"></textarea>
</div>

CSS

label {
  display: block;
}

JavaScript

$(function() {
  var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ],
    mL = 3;

  function split(val) {
    return val.split("\n");
  }

  function extractLast(term) {
    return split(term).pop();
  }

  $("#tags")
    // 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({
      minLength: mL,
      source: function(request, response) {
        // delegate back to autocomplete, but extract the last term
        var lastTerm = extractLast(request.term);
        if (lastTerm.length >= mL) {
          response($.ui.autocomplete.filter(availableTags, lastTerm));
        }
      },
      focus: function() {
        // prevent value inserted on focus
        return false;
      },
      select: function(event, ui) {
        var terms = split(this.value);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push("\u2022 " + ui.item.value);
        // Format value to display
        terms.push("");
        this.value = terms.join("\r\n");
        return false;
      }
    });
});