Tagit on input field
Using jQuery Tagit on input fields.
HTML
<script src="http://webspirited.com/tagit/js/tagit-themeroller.js"></script>
<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">
<p>This example shows how to use Tagit on an input!</p>
<input type="text" id="text" name="tags" value="one,two,three"/>
<script>
;(function ($) {
$.widget("ui.tagit", {
// default options
options:{
//Maps directly to the jQuery-ui Autocomplete option
tagSource:[],
//What keys should trigger the completion of a tag
triggerKeys:['enter', 'space', 'comma', 'tab'],
//array method for setting initial tags
initialTags:[],
//minimum length of tags
minLength:1,
//should an html select be rendered to allow for normal form submission
select:false,
//if false only tags from `tagSource` are able to be entered
allowNewt//should tag and Tag be treated as identical
caseSensitive:false,
//should tags be drag-and-drop sortable?
//true: entire tag is draggable
//'handle': a handle is rendered which is draggable
sortable:false,
//color to highlight text when a duplicate tag is entered
highlightOnExistColor:'#0F0',
//empty search on focus
emptySearch:true,
//callback function for when tags are changed
//tagValue: value of tag that was changed
//action e.g. removed, added, sorted
tagsChanged:function (tagValue, action, element) {
;
},
maxTags: undefined,
//should 'paste' event trigger 'blur', thus potentially adding a new tag
// (true for backwards compatibility)
blurOnPaste:true
},
_splitAt:/\ |,/g,
...
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);
});