Textarea Autocomplete

origin /prgtrdr/pTt2L/ How to use the standard jQuery Autocomplete widget with a text area.

by Anov Siradj

HTML

<script src="https://raw.github.com/Codecademy/textarea-helper/master/textarea-helper.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css">
<div class="ui-widget">
    <label for="tags">Tags:</label>
    <textarea id="tags" size="30"></textarea>
</div>

CSS

#tags {
     margin-top:2em;
     height:75px;
     width:90%;
     border:1px solid #000;
     font:"serif";
 }

body {
	font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
	font-size: 62.5%;
}

JavaScript

$(function() {
	$("document").ready(function() {
		// The tags we will be looking for
		var categoryTags = ["interest", "research", "personal", "social", "inventory"];
		var interestTags = ["company", "ticker", "sector", "currency", "region"];
		var researchTags = ["report", "analyst", "notes", "ideas"];
		var personalTags = ["spouse", "wife", "husband", "son", "daughter", "birthday", "anniversary", "school", "college", "university"];
		var inventoryTags = ["software", "hardware", "OMS", "EMS", "SOR", "algos", "network", "routing network"];

		// State variable to keep track of which category we are in
		tagState = categoryTags;

		// Helper functions
		function split(val) {
			return val.split( /,\s*/ );
		}

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


		$("#tags")

		// Create the autocomplete box
		.autocomplete({
			minLength : 0,
			autoFocus : true,
            source : function(request, response) {
                // Use only the last entry from the textarea (exclude previous matches)
                lastEntry = extractLast(request.term);

				var filteredArray = $.map(tagState, function(item) {
					if (item.indexOf(lastEntry) === 0) {
						return item;
					} else {
						return null;
					}
				});
               
				// delegate back to autocomplete, but extract the last term
				response($.ui.autocomplete.filter(filteredArray, lastEntry));
			},
			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(ui.item.value);
				// add placeholder to get the comma-and-space at the end
				terms.push("");
				this.value = terms.join(", ");
				return false;
			}
		}).on("keydown", function(event) {
			// don't navigate away from the field on tab when selecting an item
			if (event.keyCode === $.ui.keyCode.TAB /** &&...