articles

Home / DeveloperSection / Articles / Bootstrap Tokenfield and autocomplete

Bootstrap Tokenfield and autocomplete

Anonymous User24980 27-Jan-2015

Hi everyone in this article I’m explaining about bootstrap tokenfield and autocomplete.

Description:

JQuery Bootstrap Tokenfield is a pretty jQuery plugin that takes advantage of jQuery and Twitter's Bootstrap to manage tags / tokens in an input field.

Bootstrap Tags Input is a jQuery plugin that allows you to add, remove, and categorize tags with Twitter Bootstrap user interface.

Features:


1.       Keyboard support (arrow keys, Backspace, delete, Ctrl + A, Cmd + A, Ctrl + C, Cmd + C, Ctrl + V and Cmd + V)Copy & paste support

2.       Copy & paste support
3.       Validation states
4.       jQuery UI Autocomplete support

 

In this post describe about how to validate tag, get server side, post and autocomplete etc.

 

Open visual studio >> File >> New Project >> ASP.NET MVC 4 Web Application

 

Bootstrap Tokenfield and autocomplete

Give application name and click ok

Then after a window open and select empty template

Bootstrap Tokenfield and autocomplete

 

After create your project make database and table

Create Table TokenField
(
       Id int identity(1,1) primary key,
       Tag NVarchar(max)
)

 

Connect with database and use this table for insert tag and populate tag

Download these css and javascript files from: http: //sliptree.github.io/bootstrap-tokenfield/

<linkhref="~/Content/bootstrap/css/bootstrap.min.css"rel="stylesheet"/>
<linkhref="~/Content/bootstrap/css/bootstrap-tokenfield.min.css"rel="stylesheet"/>
<linkhref="~/Content/bootstrap/css/tokenfield-typeahead.min.css"rel="stylesheet"/>
<scriptsrc="~/Scripts/jquery-2.1.1.min.js"></script>
<scriptsrc="~/Scripts/bootstrap/js/bootstrap.min.js"></script>
<scriptsrc="~/Scripts/bootstrap/js/bootstrap-tokenfield.min.js"></script>
<scriptsrc="~/Scripts/bootstrap/js/typeahead.bundle.min.js"></script>

 

Add Controller:

HomeController Code:

using Bootstrap_TokenField.Models; 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Bootstrap_TokenField.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        MyDBEntities db = new MyDBEntities();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(TokenField model)
        {
            if (ModelState.IsValid && !string.IsNullOrEmpty(model.Tag))
            {
                db.TokenFields.Add(model);
                db.SaveChanges();
            }
            return View();
        }

        public ActionResult GetTag()
        {
            var token = string.Join(",", db.TokenFields.ToList().Select(x => x.Tag).ToList());
            return Json(new { data = token.ToString().Split(',') }, JsonRequestBehavior.AllowGet);
        }
    }
}

 

Add View:

Index Code:

@model Bootstrap_TokenField.Models.TokenField
@{
    ViewBag.Title = "Index";
}
<linkhref="~/Content/bootstrap/css/bootstrap.min.css"rel="stylesheet"/>
<linkhref="~/Content/bootstrap/css/bootstrap-tokenfield.min.css"rel="stylesheet"/>
<linkhref="~/Content/bootstrap/css/tokenfield-typeahead.min.css"rel="stylesheet"/>
<scriptsrc="~/Scripts/jquery-2.1.1.min.js"></script>
<scriptsrc="~/Scripts/bootstrap/js/bootstrap.min.js"></script>
<scriptsrc="~/Scripts/bootstrap/js/bootstrap-tokenfield.min.js"></script>
<scriptsrc="~/Scripts/bootstrap/js/typeahead.bundle.min.js"></script>
<divclass="clearfix">&nbsp;</div>
<divclass="clearfix">&nbsp;</div>
<divclass="container">
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <divclass="row">
            <divclass="col-md-4 col-md-offset-4">
                @Html.TextBoxFor(m => m.Tag, new { @class = "form-control", @id = "tokenfield" })
            </div>
        </div>
        <divclass="clearfix">&nbsp;</div>
        <divclass="row">
            <divclass="col-md-4 col-md-offset-4 text-right">
                <inputtype="submit"value="Save"class="btn btn-info"id="submittoken"/>
            </div>
        </div>
    }
</div>

 

Javascript Code:

$(document).ready(function () { 
        var token = [];
        var engine;
        $.get("Home/GetTag", function (response) {
            $.each(response.data, function (i, v) {
                token.push({ value: v });
                console.log(v);
            });
            engine = new Bloodhound({
                local: token,
                datumTokenizer: function (d) {
                    return Bloodhound.tokenizers.whitespace(d.value);
                },
                queryTokenizer: Bloodhound.tokenizers.whitespace

            });
            engine.initialize();
            console.log(token);
            $('#tokenfield').on('tokenfield:createtoken', function (e) {
                var data = e.attrs.value.split('|')
                e.attrs.value = data[1] || data[0]
                e.attrs.label = data[1] ? data[0] + ' (' + data[1] + ')' : data[0]
            }).on('tokenfield:createdtoken', function (e) {
                var re = /\S+\S+\.\S+/
                var valid = re.test(e.attrs.value)
                if (!valid) {
                    $(e.relatedTarget).addClass('invalid')
                }
            }).on('tokenfield:edittoken', function (e) {
                if (e.attrs.label !== e.attrs.value) {
                    var label = e.attrs.label.split(' (')
                    e.attrs.value = label[0] + '|' + e.attrs.value
                }
            }).on('tokenfield:removedtoken', function (e) {
            }).tokenfield({
                typeahead: [null, { source: engine.ttAdapter() }]
            });
        });
    });
 
Output:

Bootstrap Tokenfield and autocomplete


In my next post i'll explain about CheckBoxList Example in ASP.NET MVC 4


I am a content writter !

Leave Comment

Comments

Liked By