Textarea Autocomplete
How to use the standard jQuery Autocomplete widget with a text area.
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">
<textarea id="tags" size="30"></textarea>
CSS
#tags {
margin-top:2em;
height:100px;
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"];
// State variable to keep track of which category we are in
tagState = categoryTags;
// Helper functions
function split(val) {
return val.split( "\n" );
}
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("\n");
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 /** && $(this).data("ui-autocomplete").menu.active **/) {
event.preventDefault();
return;
}
// Code to position and move the selection box as the user types
var newY = $(this).textareaHelper('caretPos').top + (parseInt($(this).css('font-size'), 10) * 1.5);
var newX = $(this).textareaHelper('caretPos').left;
var posString = "left+" + newX + "px top+" + newY +...