Monday, March 23, 2015

Making Bootstrap Tags Input to prevent repeating Tag with same word

Bootstrap tags input is applied by developer for managing tag by user. Tag is a label attached to  someone or something for the purpose of identification or give other information for the purpose of grouping, marking and so forth. It allows new tag to be added regarding its case sensitive if the identical tag has been added to prevent repeating. However, for some intents further require the tag to be filtered if they are same word regardless of case sensitive. For Example: "Hello World" is treated as same word as "hello world", and Bootstrap Tags Input in nature will take them as different tags to be added into tagging list.


Sample of Bootstrap Tags Input:
Amsterdam Washington Sydney Beijing 

When Cairo 'Tag' is entered, the Tag is added into the tagging list:
Amsterdam Washington Sydney Beijing Cairo 


Therefore, below are the snippet of codes show on how to prevent tag with same word to be added into tagging list.



HTML:

<input class="span12 tagsinput" id="addinputtag" type="text" value="" data-role="tagsinput" />


JS:

$("#addinputtag").on('itemAdded', function(event) {


    var workspaceNameuppcase = event.item.toUpperCase();
    var temp = $("#addinputtag").tagsinput('items');
    var duplicatecount = 0;
    temp.forEach(function(tag) {

        if (workspaceNameuppcase === tag.toUpperCase())
        {

            duplicatecount += 1;
        }

    });                               

    //remove duplication
    if (duplicatecount > 1)
    {
        $("#addinputtag").tagsinput('remove', event.item);

    }

     .
     .
     .


 }


Explanation:

"itemAdded" Event is invoked when an item is added into Bootstrap Tags Input. By going through this event, the new added item is retrieved and compared against the tagging list in it. if they are found same word, the new added item required to be removed. This filtering step is applied in the post event when item is added into the list. It would be great if there is pre-event applicable when input text is changed before the item is added.