You are on page 1of 9

22/09/2015

jQuery Tokeninput

JamesSmith

jQueryTokeninput
AjQueryTokenizingAutocompleteTextEntry

Fork

982

Tweet

InstantDemo

Download
version 1.6.0 (latest)

orforkmeongithub

StarttypingTVshownamesintheboxabove.
Moredemoscanbefoundhere.

Overview
TokeninputisajQuerypluginwhichallowsyouruserstoselectmultipleitemsfromapredefined
list,usingautocompletionastheytypetofindeachitem.Youmayhaveseenasimilartypeoftext
entrywhenfillingintherecipientsfieldsendingmessagesonfacebook.

Features
IntuitiveUIforselectingmultipleitemsfromalargelist
http://loopj.com/jquery-tokeninput/

1/9

22/09/2015

jQuery Tokeninput

Easytoskin/stylepurelyincss,noimagesrequired
SupportsanybackendwhichcangenerateJSON,includingPHP,Rails,Django,ASP.net
Smoothanimationswhenresultsload
Select,deleteandnavigateitemsusingthemouseorkeyboard
Clientsideresultcachingtoreduceserverload
CrossdomainsupportviaJSONP
Callbackswhenitemsareaddedorremovedfromthelist
PreprocessresultsfromtheserverwiththeonResultcallback
Programaticallyadd,remove,clearandgettokens
Customizetheoutputformatoftheresultsandtokens

Screenshots

Verticalliststyleitemselection

Facebookstyleitemselection
http://loopj.com/jquery-tokeninput/

2/9

22/09/2015

jQuery Tokeninput

Installation&Setup
Createaserversidescripttohandlesearchrequests
Createaserversidescript(PHP,Rails,ASP.net,etc)togenerateyoursearchresults.Thescriptcan
fetchdatafromwhereveryoulike,forexampleadatabaseorahardcodedlist.Yourscriptmust
acceptaGETparameternamedqwhichwillcontainthetermtosearchfor.E.g.
http://www.example.com/myscript?q=query
YourscriptshouldoutputJSONsearchresultsinthefollowingformat:
[

{"id":"856","name":"House"},
{"id":"1035","name":"Desperate Housewives"},
...

Youmayoptionallyspecifyanattributeofreadonlyandsetittotrueifyouwouldlikesomeof
thetokenstobenonremovable:
[

{"id":"856","name":"House","readonly":true},
{"id":"1035","name":"Desperate Housewives"},
...

Notethatyoumayomitreadonlyonentitieswhereitisnotnecessary.Thisattributeisacceptable
whereverJSONentitiesarepassed,e.g..tokenInput(add)(seeMethodssectionbelow).
Includeandinitializetheplugin
IncludejQueryandTokeninputJavascriptandstylesheetfilesonyourpage,andattachtoyourtext
http://loopj.com/jquery-tokeninput/

3/9

22/09/2015

jQuery Tokeninput

input:Tokeninputstylesheet:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>


<script type="text/javascript" src="yourfiles/jquery.tokeninput.js"></script>
<link rel="stylesheet" type="text/css" href="yourfiles/token-input.css" />
<script type="text/javascript">
$(document).ready(function () {
$("#my-text-input").tokenInput("/url/to/your/script/");
});
</script>

Configuration
Thetokeninputtakesanoptionalsecondparameteronintitializationwhichallowsyoutocustomize
theappearanceandbehaviourofthescript,aswellasaddyourowncallbackstointerceptcertain
events.Thefollowingoptionsareavailable:
SearchSettings
method
TheHTTPmethod(eg.GET,POST)tousefortheserverrequest.default:GET.
queryParam
Thenameofthequeryparamwhichyouexpecttocontainthesearchtermontheserverside.
default:q.
searchDelay
Thedelay,inmilliseconds,betweentheuserfinishingtypingandthesearchbeingperformed.
default:300(demo).
minChars
http://loopj.com/jquery-tokeninput/

4/9

22/09/2015

jQuery Tokeninput

Theminimumnumberofcharacterstheusermustenterbeforeasearchisperformed.default:1
(demo).
propertyToSearch
Thejavascript/jsonobjectattributetosearch.default:name(demo).
jsonContainer
Thenameofthejsonobjectintheresponsewhichcontainsthesearchresults.Thisistypically
usedwhenyourendpointreturnsotherdatainadditiontoyoursearchresults.Usenulltouse
thetoplevelresponseobject.default:null.
crossDomain
ForceJSONPcrossdomaincommunicationtotheserverinsteadofanormalajaxrequest.Note:
JSONPisautomaticallyenabledifwedetectthesearchrequestisacrossdomainrequest.
default:false.
PrepopulationSettings
prePopulate
Prepopulatethetokeninputwithexistingdata.SettoanarrayofJSONobjects,eg:[{id: 3,
name: "test"}, {id: 5, name: "awesome"}]toprefilltheinput.default:null(demo).
DisplaySettings
hintText
Thetexttoshowinthedropdownlabelwhichappearswhenyoufirstclickinthesearchfield.
default:Typeinasearchterm(demo).
noResultsText
Thetexttoshowinthedropdownlabelwhennoresultsarefoundwhichmatchthecurrent
query.default:Noresults(demo).
http://loopj.com/jquery-tokeninput/

5/9

22/09/2015

jQuery Tokeninput

searchingText
Thetexttoshowinthedropdownlabelwhenasearchiscurrentlyinprogress.default:
Searching(demo).
deleteText
Thetexttoshowoneachtokenwhichdeletesthetokenwhenclicked.Ifyouwishtohidethe
deletelink,provideanemptystringhere.Alternativelyyoucanprovideahtmlstringhereifyou
wouldliketoshowanimagefordeletingtokens.default:(demo).
animateDropdown
Setthistofalsetodisableanimationofthedropdowndefault:true(demo).
theme
Setthistoastring,egfacebookwhenincludingthemecssfilestosetthecssclasssuffix
(demo).
resultsLimit
Themaximumnumberofresultsshowninthedropdown.Usenulltoshowallthematching
results.default:null
resultsFormatter
AfunctionthatreturnsaninterpolatedHTMLstringforeachresult.Usethisfunctionwitha
templatingsystemofyourchoice,suchasjresigmicrotemplatesormustache.js.Usethiswhen
youwanttoincludeimagesormultilineformattedresultsdefault:function(item){return<li>
+item.propertyToSearch+</li>}(demo).
tokenFormatter
AfunctionthatreturnsaninterpolatedHTMLstringforeachtoken.Usethisfunctionwitha
templatingsystemofyourchoice,suchasjresigmicrotemplatesormustache.js.Usethiswhen
youwanttoincludeimagesormultilineformattedtokens.Quoraspeopleinvitetokenfieldthat
returnsavatartokensisagoodexampleofwhatcanbedonethisoption.default:function(item){
http://loopj.com/jquery-tokeninput/

6/9

22/09/2015

jQuery Tokeninput

return<li><p>+item.propertyToSearch+</p></li>}(demo).
TokenizationSettings
tokenLimit
Themaximumnumberofresultsallowedtobeselectedbytheuser.Usenulltoallow
unlimitedselections.default:null(demo).
tokenDelimiter
Theseparatortousewhensendingtheresultsbacktotheserver.default:,.
preventDuplicates
Preventuserfromselectingduplicatevaluesbysettingthistotrue.default:false(demo).
tokenValue
Thevalueofthetokeninputwhentheinputissubmitted.Setittoidinordertogeta
concatenationoftokenIDs,ortonameinordertogetaconcatenationofnames.default:id
Callbacks
onResult
Afunctiontocallwheneverwereceiveresultsbackfromtheserver.Youcanusethisfunction
topreprocessresultsfromtheserverbeforetheyaredisplayedtotheuser.default:null(demo).
onAdd
Afunctiontocallwhenevertheuseraddsanothertokentotheirselections.defaut:null(demo).
onDelete
Afunctiontocallwhenevertheuserremovesatokenfromtheirselections.default:null(demo).
onReady
http://loopj.com/jquery-tokeninput/

7/9

22/09/2015

jQuery Tokeninput

Afunctiontocallafterinitializationisdoneandthetokeninputisreadytouse.default:null

Methods
selector.tokenInput("add", {id: x, name: y});

Addanewtokentothetokeninputwithidxandnamey.
selector.tokenInput("remove", {id: x});

Removethetokenswithidxfromthetokeninput.
selector.tokenInput("remove", {name: y});

Removethetokenswithnameyfromthetokeninput.
selector.tokenInput("clear");

Clearalltokensfromthetokeninput.
selector.tokenInput("get");

Getsthearrayofselectedtokensfromthetokeninput(eachitembeinganobjectofthekind
{id: x, name: y}).

ReportingBugsorFeatureRequests
Pleasereportanybugsorfeaturerequestsonthegithubissuespageforthisprojecthere:
https://github.com/loopj/jquerytokeninput/issues

License
http://loopj.com/jquery-tokeninput/

8/9

22/09/2015

jQuery Tokeninput

Tokeninputisreleasedunderaduallicense.YoucanchooseeithertheGPLorMITlicense
dependingontheprojectyouareusingitinandhowyouwishtouseit.

AbouttheAuthor
JamesSmith,BritishentrepreneuranddeveloperbasedinSanFrancisco.
I'mthecofounderofBugsnagwithSimonMaynard,andfrom2009to2012Ileduptheproduct
teamasCTOofHeyzap.
Follow@loopj

http://loopj.com/jquery-tokeninput/

9/9

You might also like