JQuery TypeTags

A simple tag manager for JQuery that work nicely with twitter typeahead

by Ludovico Mattiuzzo

HTML

<input type="hidden" id="tag-hidden" value="one tag,another tag" />
<div id="tag-list"></div>
<input id="tag-input" type="text" value="" class="form-control" />

CSS

.type-tag {
  display: inline-block;
  border-radius: 3px;
  color: #228B22;
  background-color: #98FB98;
  font-size: 13px;
  margin: 0 5px 5px 0;
  padding: 4px;
}

.type-tag a {
  color: #000000;
  font-weight: bold;
  margin-left: 4px;
  opacity: 0.2;
}

.type-tag a:hover {
  color: #000000;
  text-decoration: none;
  opacity: 0.4;
}

#tag-list {
  padding: 10px;
  display: inline-block;
}

JavaScript

(function($) {

  $.typeTags = function(element, options) {

    var defaults = {
      delimiters: [9, 13, 44], // tab, enter, comma
      containerSelector: "",
      hiddenSelector: "",
      deleteOnBackspace: true
    }

    var plugin = this;

    plugin.settings = {}

    var $element = $(element),
      element = element;

    var tagList = [];

    plugin.init = function() {
      plugin.settings = $.extend({}, defaults, options);

      prefill();

      $element.keypress(function(e) {
        if (keyInArray(e, plugin.settings.delimiters)) {
          plugin.pushTag($element.val());
          killEvent(e);
        }
      });

      $element.keydown(function(e) {
        if (plugin.settings.deleteOnBackspace && e.which == 8 && $(this).val() == '') {
          if (tagList.length > 0) {
            removeTag(tagList[tagList.length - 1].tagNode, true);
            killEvent(e);
          }
        }
        if (e.which == 9 && keyInArray(e, plugin.settings.delimiters)) // tasto tab
        {
          plugin.pushTag($element.val());
          killEvent(e);
        }
      });


      // gestione typeahead. Al select aggiungo un tag e svuoto il valore
      $element.bind('typeahead:select', function(ev, suggestion) {
        plugin.pushTag($element.typeahead('val'), suggestion);
        $element.typeahead('val', '');
      });

    }

    plugin.clear = function() {
      tagList = [];
      clearInput();
      $(plugin.settings.containerSelector).html('');
      $(plugin.settings.hiddenSelector).val('');
    }

    plugin.pushTag = function(tagText, typeaheadSuggestion) {
      // non inserire duplicati
      if (tagText == "")
        return;
      for (var i = 0; i < tagList.length; i++) {
        if (tagList[i].text.toLowerCase() === tagText.toLowerCase()) {
          return;
        }
      }

      var html = '';
      html += '<div class="type-tag">';
      html += '<span>' + tagText + '</span>';
      html += '<a href="#" class="tag-remove">x</a>';
...