Tagit on input field - AUTOCOMPLETE EXAMPLE

Using jQuery Tagit on input fields.

by bizamajig

HTML

<link rel="stylesheet" href="http://webspirited.com/tagit/css/themeroller/bootstrap/Bootstrap.css">
<link rel="stylesheet" href="http://webspirited.com/tagit/css/themeroller/tagit.css">
<script src="http://webspirited.com/tagit/js/tagit-themeroller.js"></script>
<p>This example shows how to use Tagit on an input!</p>
<input type="text" id="text" name="tags" value="one,two,three"/>

JavaScript

$(document).ready(function() {

  //The demo tag array
  var availableTags = [
    {id: 1, label: 'tag1'},
    {id: 2, label: 'tag2'},
    {id: 3, label: 'tag3'}];
    
  //The text input
  var input = $("input#text");
    
  //The tagit list
  var instance = $("<ul class=\"tags\"></ul>");
    
  //Store the current tags
  //Note: the tags here can be split by any of the trigger keys
  //      as tagit will split on the trigger keys anything passed  
  var currentTags = input.val();
    
  //Hide the input and append tagit to the dom
  input.hide().after(instance);
    
  //Initialize tagit
  instance.tagit({
    tagSource:availableTags,
    tagsChanged:function () {
                                        
      //Get the tags            
      var tags = instance.tagit('tags');
      var tagString = [];
                            
      //Pull out only value
      for (var i in tags){
        tagString.push(tags[i].value);
      }
        
      //Put the tags into the input, joint by a ','
      input.val(tagString.join(','));

    alert('Tags are: ' + input.val());


    }
  });
    
  //Add pre-loaded tags to tagit
  instance.tagit('add', currentTags);
    
    
});