Tagit on input field an arrayd alert

Using jQuery Tagit on input fields.

by karimkhan

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">
<input type="text" id="text" name="tags" value="" />
<button>Pretend Submit Button</button>

CSS

ul.tagit.ui-widget li.tagit-choice {
    display: block;
    float: left;
    position: relative;
    line-height: inherit;
    border-radius: 6px;
    background-color: #EFEFEF;
    border: 1px solid #DDD;
    padding: 5px;
    margin-right: 10px;
    color: #08c;
    text-decoration: none;
}
ul.tagit.ui-widget li.tagit-choice a.tagit-close {
    cursor: pointer;
    position: absolute;
    right: 5px;
    top: 50%;
    margin-top: -8px;
    display: none;
}

JavaScript

$(document).ready(function () {
     tagsForPost = [];
    //The demo tag array
    var availableTags = [{
        value: 1,
        label: 'tag1'
    }, {
        value: 2,
        label: 'tag2'
    }, {
        value: 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);

            }
            //alert(tags.value);
            //Put the tags into the input, joint by a ','
            input.val(tagString.join(','));
        }
    });
    //alert(currentTags);
    //Add pre-loaded tags to tagit
    instance.tagit('add', currentTags);
    
    
    ///just to show how to retrieve the values...
    $('button').on('click', function () {
        
       
        $('.tagit-choice').each(function (i) {
             tagObj = {value: i, label: $(this).contents(':not(a)').text()};
             tagsForPost.push(tagObj);
        });
        console.log(tagsForPost);
        alert(JSON.stringify(tagsForPost));
        //alert(tagsForPost.join('\n'))
        //alert( $.toJSON(tagsForPost) );
    });
});