select2.js 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348
  1. /*
  2. Copyright 2012 Igor Vaynberg
  3. Version: @@ver@@ Timestamp: @@timestamp@@
  4. This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
  5. General Public License version 2 (the "GPL License"). You may choose either license to govern your
  6. use of this software only upon the condition that you accept all of the terms of either the Apache
  7. License or the GPL License.
  8. You may obtain a copy of the Apache License and the GPL License at:
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. http://www.gnu.org/licenses/gpl-2.0.html
  11. Unless required by applicable law or agreed to in writing, software distributed under the
  12. Apache License or the GPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for
  14. the specific language governing permissions and limitations under the Apache License and the GPL License.
  15. */
  16. (function ($) {
  17. if(typeof $.fn.each2 == "undefined") {
  18. $.extend($.fn, {
  19. /*
  20. * 4-10 times faster .each replacement
  21. * use it carefully, as it overrides jQuery context of element on each iteration
  22. */
  23. each2 : function (c) {
  24. var j = $([0]), i = -1, l = this.length;
  25. while (
  26. ++i < l
  27. && (j.context = j[0] = this[i])
  28. && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
  29. );
  30. return this;
  31. }
  32. });
  33. }
  34. })(jQuery);
  35. (function ($, undefined) {
  36. "use strict";
  37. /*global document, window, jQuery, console */
  38. if (window.Select2 !== undefined) {
  39. return;
  40. }
  41. var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer,
  42. lastMousePosition={x:0,y:0}, $document, scrollBarDimensions,
  43. KEY = {
  44. TAB: 9,
  45. ENTER: 13,
  46. ESC: 27,
  47. SPACE: 32,
  48. LEFT: 37,
  49. UP: 38,
  50. RIGHT: 39,
  51. DOWN: 40,
  52. SHIFT: 16,
  53. CTRL: 17,
  54. ALT: 18,
  55. PAGE_UP: 33,
  56. PAGE_DOWN: 34,
  57. HOME: 36,
  58. END: 35,
  59. BACKSPACE: 8,
  60. DELETE: 46,
  61. isArrow: function (k) {
  62. k = k.which ? k.which : k;
  63. switch (k) {
  64. case KEY.LEFT:
  65. case KEY.RIGHT:
  66. case KEY.UP:
  67. case KEY.DOWN:
  68. return true;
  69. }
  70. return false;
  71. },
  72. isControl: function (e) {
  73. var k = e.which;
  74. switch (k) {
  75. case KEY.SHIFT:
  76. case KEY.CTRL:
  77. case KEY.ALT:
  78. return true;
  79. }
  80. if (e.metaKey) return true;
  81. return false;
  82. },
  83. isFunctionKey: function (k) {
  84. k = k.which ? k.which : k;
  85. return k >= 112 && k <= 123;
  86. }
  87. },
  88. MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>",
  89. DIACRITICS = {"\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A","\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A","\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A","\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A","\u2C6F":"A","\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV","\uA73C":"AY","\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24B8":"C","\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C","\u023B":"C","\uA73E":"C","\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D","\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D","\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz","\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E","\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E","\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E","\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E","\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F","\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G","\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G","\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H","\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H","\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I","\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I","\u012E":"I","\u1E2C":"I","\u0197":"I","\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J","\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K","\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K","\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L","\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L","\uA780":"L","\u01C7":"LJ","\u01C8":"Lj","\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M","\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N","\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N","\u01CA":"NJ","\u01CB":"Nj","\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O","\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O","\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O","\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O","\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O","\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU","\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P","\uA754":"P","\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q","\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R","\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R","\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S","\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S","\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T","\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ","\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U","\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U","\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U","\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U","\u0244":"U","\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY","\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W","\u2C72":"W","\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X","\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y","\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y","\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z","\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z","\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a","\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a","\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a","\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a","\u2C65":"a","\u0250":"a","\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av","\uA73D":"ay","\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c","\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c","\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d","\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz","\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e","\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e","\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e","\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e","\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f","\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g","\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g","\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h","\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv","\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i","\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i","\u1E2D":"i","\u0268":"i","\u0131":"i","\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j","\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k","\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k","\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l","\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l","\uA781":"l","\uA747":"l","\u01C9":"lj","\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m","\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n","\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n","\u01CC":"nj","\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o","\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o","\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o","\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o","\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o","\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo","\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p","\uA755":"p","\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q","\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r","\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r","\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s","\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s","\u1E9B":"s","\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t","\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz","\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u","\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u","\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u","\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u","\u0289":"u","\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy","\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w","\u1E89":"w","\u2C73":"w","\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y","\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y","\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z","\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z"};
  90. $document = $(document);
  91. nextUid=(function() { var counter=1; return function() { return counter++; }; }());
  92. function reinsertElement(element) {
  93. var placeholder = $(document.createTextNode(''));
  94. element.before(placeholder);
  95. placeholder.before(element);
  96. placeholder.remove();
  97. }
  98. function stripDiacritics(str) {
  99. var ret, i, l, c;
  100. if (!str || str.length < 1) return str;
  101. ret = "";
  102. for (i = 0, l = str.length; i < l; i++) {
  103. c = str.charAt(i);
  104. ret += DIACRITICS[c] || c;
  105. }
  106. return ret;
  107. }
  108. function indexOf(value, array) {
  109. var i = 0, l = array.length;
  110. for (; i < l; i = i + 1) {
  111. if (equal(value, array[i])) return i;
  112. }
  113. return -1;
  114. }
  115. function measureScrollbar () {
  116. var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
  117. $template.appendTo('body');
  118. var dim = {
  119. width: $template.width() - $template[0].clientWidth,
  120. height: $template.height() - $template[0].clientHeight
  121. };
  122. $template.remove();
  123. return dim;
  124. }
  125. /**
  126. * Compares equality of a and b
  127. * @param a
  128. * @param b
  129. */
  130. function equal(a, b) {
  131. if (a === b) return true;
  132. if (a === undefined || b === undefined) return false;
  133. if (a === null || b === null) return false;
  134. // Check whether 'a' or 'b' is a string (primitive or object).
  135. // The concatenation of an empty string (+'') converts its argument to a string's primitive.
  136. if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object
  137. if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object
  138. return false;
  139. }
  140. /**
  141. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  142. * strings
  143. * @param string
  144. * @param separator
  145. */
  146. function splitVal(string, separator) {
  147. var val, i, l;
  148. if (string === null || string.length < 1) return [];
  149. val = string.split(separator);
  150. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  151. return val;
  152. }
  153. function getSideBorderPadding(element) {
  154. return element.outerWidth(false) - element.width();
  155. }
  156. function installKeyUpChangeEvent(element) {
  157. var key="keyup-change-value";
  158. element.on("keydown", function () {
  159. if ($.data(element, key) === undefined) {
  160. $.data(element, key, element.val());
  161. }
  162. });
  163. element.on("keyup", function () {
  164. var val= $.data(element, key);
  165. if (val !== undefined && element.val() !== val) {
  166. $.removeData(element, key);
  167. element.trigger("keyup-change");
  168. }
  169. });
  170. }
  171. $document.on("mousemove", function (e) {
  172. lastMousePosition.x = e.pageX;
  173. lastMousePosition.y = e.pageY;
  174. });
  175. /**
  176. * filters mouse events so an event is fired only if the mouse moved.
  177. *
  178. * filters out mouse events that occur when mouse is stationary but
  179. * the elements under the pointer are scrolled.
  180. */
  181. function installFilteredMouseMove(element) {
  182. element.on("mousemove", function (e) {
  183. var lastpos = lastMousePosition;
  184. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  185. $(e.target).trigger("mousemove-filtered", e);
  186. }
  187. });
  188. }
  189. /**
  190. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  191. * within the last quietMillis milliseconds.
  192. *
  193. * @param quietMillis number of milliseconds to wait before invoking fn
  194. * @param fn function to be debounced
  195. * @param ctx object to be used as this reference within fn
  196. * @return debounced version of fn
  197. */
  198. function debounce(quietMillis, fn, ctx) {
  199. ctx = ctx || undefined;
  200. var timeout;
  201. return function () {
  202. var args = arguments;
  203. window.clearTimeout(timeout);
  204. timeout = window.setTimeout(function() {
  205. fn.apply(ctx, args);
  206. }, quietMillis);
  207. };
  208. }
  209. /**
  210. * A simple implementation of a thunk
  211. * @param formula function used to lazily initialize the thunk
  212. * @return {Function}
  213. */
  214. function thunk(formula) {
  215. var evaluated = false,
  216. value;
  217. return function() {
  218. if (evaluated === false) { value = formula(); evaluated = true; }
  219. return value;
  220. };
  221. };
  222. function installDebouncedScroll(threshold, element) {
  223. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  224. element.on("scroll", function (e) {
  225. if (indexOf(e.target, element.get()) >= 0) notify(e);
  226. });
  227. }
  228. function focus($el) {
  229. if ($el[0] === document.activeElement) return;
  230. /* set the focus in a 0 timeout - that way the focus is set after the processing
  231. of the current event has finished - which seems like the only reliable way
  232. to set focus */
  233. window.setTimeout(function() {
  234. var el=$el[0], pos=$el.val().length, range;
  235. $el.focus();
  236. /* make sure el received focus so we do not error out when trying to manipulate the caret.
  237. sometimes modals or others listeners may steal it after its set */
  238. if ($el.is(":visible") && el === document.activeElement) {
  239. /* after the focus is set move the caret to the end, necessary when we val()
  240. just before setting focus */
  241. if(el.setSelectionRange)
  242. {
  243. el.setSelectionRange(pos, pos);
  244. }
  245. else if (el.createTextRange) {
  246. range = el.createTextRange();
  247. range.collapse(false);
  248. range.select();
  249. }
  250. }
  251. }, 0);
  252. }
  253. function getCursorInfo(el) {
  254. el = $(el)[0];
  255. var offset = 0;
  256. var length = 0;
  257. if ('selectionStart' in el) {
  258. offset = el.selectionStart;
  259. length = el.selectionEnd - offset;
  260. } else if ('selection' in document) {
  261. el.focus();
  262. var sel = document.selection.createRange();
  263. length = document.selection.createRange().text.length;
  264. sel.moveStart('character', -el.value.length);
  265. offset = sel.text.length - length;
  266. }
  267. return { offset: offset, length: length };
  268. }
  269. function killEvent(event) {
  270. event.preventDefault();
  271. event.stopPropagation();
  272. }
  273. function killEventImmediately(event) {
  274. event.preventDefault();
  275. event.stopImmediatePropagation();
  276. }
  277. function measureTextWidth(e) {
  278. if (!sizer){
  279. var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
  280. sizer = $(document.createElement("div")).css({
  281. position: "absolute",
  282. left: "-10000px",
  283. top: "-10000px",
  284. display: "none",
  285. fontSize: style.fontSize,
  286. fontFamily: style.fontFamily,
  287. fontStyle: style.fontStyle,
  288. fontWeight: style.fontWeight,
  289. letterSpacing: style.letterSpacing,
  290. textTransform: style.textTransform,
  291. whiteSpace: "nowrap"
  292. });
  293. sizer.attr("class","select2-sizer");
  294. $("body").append(sizer);
  295. }
  296. sizer.text(e.val());
  297. return sizer.width();
  298. }
  299. function syncCssClasses(dest, src, adapter) {
  300. var classes, replacements = [], adapted;
  301. classes = dest.attr("class");
  302. if (classes) {
  303. classes = '' + classes; // for IE which returns object
  304. $(classes.split(" ")).each2(function() {
  305. if (this.indexOf("select2-") === 0) {
  306. replacements.push(this);
  307. }
  308. });
  309. }
  310. classes = src.attr("class");
  311. if (classes) {
  312. classes = '' + classes; // for IE which returns object
  313. $(classes.split(" ")).each2(function() {
  314. if (this.indexOf("select2-") !== 0) {
  315. adapted = adapter(this);
  316. if (adapted) {
  317. replacements.push(adapted);
  318. }
  319. }
  320. });
  321. }
  322. dest.attr("class", replacements.join(" "));
  323. }
  324. function markMatch(text, term, markup, escapeMarkup) {
  325. var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())),
  326. tl=term.length;
  327. if (match<0) {
  328. markup.push(escapeMarkup(text));
  329. return;
  330. }
  331. markup.push(escapeMarkup(text.substring(0, match)));
  332. markup.push("<span class='select2-match'>");
  333. markup.push(escapeMarkup(text.substring(match, match + tl)));
  334. markup.push("</span>");
  335. markup.push(escapeMarkup(text.substring(match + tl, text.length)));
  336. }
  337. function defaultEscapeMarkup(markup) {
  338. var replace_map = {
  339. '\\': '&#92;',
  340. '&': '&amp;',
  341. '<': '&lt;',
  342. '>': '&gt;',
  343. '"': '&quot;',
  344. "'": '&#39;',
  345. "/": '&#47;'
  346. };
  347. return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
  348. return replace_map[match];
  349. });
  350. }
  351. /**
  352. * Produces an ajax-based query function
  353. *
  354. * @param options object containing configuration parameters
  355. * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax
  356. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  357. * @param options.url url for the data
  358. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  359. * @param options.dataType request data type: ajax, jsonp, other datatypes supported by jQuery's $.ajax function or the transport function if specified
  360. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  361. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  362. * The expected format is an object containing the following keys:
  363. * results array of objects that will be used as choices
  364. * more (optional) boolean indicating whether there are more results available
  365. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  366. */
  367. function ajax(options) {
  368. var timeout, // current scheduled but not yet executed request
  369. handler = null,
  370. quietMillis = options.quietMillis || 100,
  371. ajaxUrl = options.url,
  372. self = this;
  373. return function (query) {
  374. window.clearTimeout(timeout);
  375. timeout = window.setTimeout(function () {
  376. var data = options.data, // ajax data function
  377. url = ajaxUrl, // ajax url string or function
  378. transport = options.transport || $.fn.select2.ajaxDefaults.transport,
  379. // deprecated - to be removed in 4.0 - use params instead
  380. deprecated = {
  381. type: options.type || 'GET', // set type of request (GET or POST)
  382. cache: options.cache || false,
  383. jsonpCallback: options.jsonpCallback||undefined,
  384. dataType: options.dataType||"json"
  385. },
  386. params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
  387. data = data ? data.call(self, query.term, query.page, query.context) : null;
  388. url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
  389. if (handler && typeof handler.abort === "function") { handler.abort(); }
  390. if (options.params) {
  391. if ($.isFunction(options.params)) {
  392. $.extend(params, options.params.call(self));
  393. } else {
  394. $.extend(params, options.params);
  395. }
  396. }
  397. $.extend(params, {
  398. url: url,
  399. dataType: options.dataType,
  400. data: data,
  401. success: function (data) {
  402. // TODO - replace query.page with query so users have access to term, page, etc.
  403. var results = options.results(data, query.page);
  404. query.callback(results);
  405. }
  406. });
  407. handler = transport.call(self, params);
  408. }, quietMillis);
  409. };
  410. }
  411. /**
  412. * Produces a query function that works with a local array
  413. *
  414. * @param options object containing configuration parameters. The options parameter can either be an array or an
  415. * object.
  416. *
  417. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  418. *
  419. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  420. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  421. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  422. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  423. * the text.
  424. */
  425. function local(options) {
  426. var data = options, // data elements
  427. dataText,
  428. tmp,
  429. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  430. if ($.isArray(data)) {
  431. tmp = data;
  432. data = { results: tmp };
  433. }
  434. if ($.isFunction(data) === false) {
  435. tmp = data;
  436. data = function() { return tmp; };
  437. }
  438. var dataItem = data();
  439. if (dataItem.text) {
  440. text = dataItem.text;
  441. // if text is not a function we assume it to be a key name
  442. if (!$.isFunction(text)) {
  443. dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available
  444. text = function (item) { return item[dataText]; };
  445. }
  446. }
  447. return function (query) {
  448. var t = query.term, filtered = { results: [] }, process;
  449. if (t === "") {
  450. query.callback(data());
  451. return;
  452. }
  453. process = function(datum, collection) {
  454. var group, attr;
  455. datum = datum[0];
  456. if (datum.children) {
  457. group = {};
  458. for (attr in datum) {
  459. if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
  460. }
  461. group.children=[];
  462. $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
  463. if (group.children.length || query.matcher(t, text(group), datum)) {
  464. collection.push(group);
  465. }
  466. } else {
  467. if (query.matcher(t, text(datum), datum)) {
  468. collection.push(datum);
  469. }
  470. }
  471. };
  472. $(data().results).each2(function(i, datum) { process(datum, filtered.results); });
  473. query.callback(filtered);
  474. };
  475. }
  476. // TODO javadoc
  477. function tags(data) {
  478. var isFunc = $.isFunction(data);
  479. return function (query) {
  480. var t = query.term, filtered = {results: []};
  481. $(isFunc ? data() : data).each(function () {
  482. var isObject = this.text !== undefined,
  483. text = isObject ? this.text : this;
  484. if (t === "" || query.matcher(t, text)) {
  485. filtered.results.push(isObject ? this : {id: this, text: this});
  486. }
  487. });
  488. query.callback(filtered);
  489. };
  490. }
  491. /**
  492. * Checks if the formatter function should be used.
  493. *
  494. * Throws an error if it is not a function. Returns true if it should be used,
  495. * false if no formatting should be performed.
  496. *
  497. * @param formatter
  498. */
  499. function checkFormatter(formatter, formatterName) {
  500. if ($.isFunction(formatter)) return true;
  501. if (!formatter) return false;
  502. throw new Error(formatterName +" must be a function or a falsy value");
  503. }
  504. function evaluate(val) {
  505. return $.isFunction(val) ? val() : val;
  506. }
  507. function countResults(results) {
  508. var count = 0;
  509. $.each(results, function(i, item) {
  510. if (item.children) {
  511. count += countResults(item.children);
  512. } else {
  513. count++;
  514. }
  515. });
  516. return count;
  517. }
  518. /**
  519. * Default tokenizer. This function uses breaks the input on substring match of any string from the
  520. * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
  521. * two options have to be defined in order for the tokenizer to work.
  522. *
  523. * @param input text user has typed so far or pasted into the search field
  524. * @param selection currently selected choices
  525. * @param selectCallback function(choice) callback tho add the choice to selection
  526. * @param opts select2's opts
  527. * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
  528. */
  529. function defaultTokenizer(input, selection, selectCallback, opts) {
  530. var original = input, // store the original so we can compare and know if we need to tell the search to update its text
  531. dupe = false, // check for whether a token we extracted represents a duplicate selected choice
  532. token, // token
  533. index, // position at which the separator was found
  534. i, l, // looping variables
  535. separator; // the matched separator
  536. if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
  537. while (true) {
  538. index = -1;
  539. for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
  540. separator = opts.tokenSeparators[i];
  541. index = input.indexOf(separator);
  542. if (index >= 0) break;
  543. }
  544. if (index < 0) break; // did not find any token separator in the input string, bail
  545. token = input.substring(0, index);
  546. input = input.substring(index + separator.length);
  547. if (token.length > 0) {
  548. token = opts.createSearchChoice.call(this, token, selection);
  549. if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
  550. dupe = false;
  551. for (i = 0, l = selection.length; i < l; i++) {
  552. if (equal(opts.id(token), opts.id(selection[i]))) {
  553. dupe = true; break;
  554. }
  555. }
  556. if (!dupe) selectCallback(token);
  557. }
  558. }
  559. }
  560. if (original!==input) return input;
  561. }
  562. /**
  563. * Creates a new class
  564. *
  565. * @param superClass
  566. * @param methods
  567. */
  568. function clazz(SuperClass, methods) {
  569. var constructor = function () {};
  570. constructor.prototype = new SuperClass;
  571. constructor.prototype.constructor = constructor;
  572. constructor.prototype.parent = SuperClass.prototype;
  573. constructor.prototype = $.extend(constructor.prototype, methods);
  574. return constructor;
  575. }
  576. AbstractSelect2 = clazz(Object, {
  577. // abstract
  578. bind: function (func) {
  579. var self = this;
  580. return function () {
  581. func.apply(self, arguments);
  582. };
  583. },
  584. // abstract
  585. init: function (opts) {
  586. var results, search, resultsSelector = ".select2-results";
  587. // prepare options
  588. this.opts = opts = this.prepareOpts(opts);
  589. this.id=opts.id;
  590. // destroy if called on an existing component
  591. if (opts.element.data("select2") !== undefined &&
  592. opts.element.data("select2") !== null) {
  593. opts.element.data("select2").destroy();
  594. }
  595. this.container = this.createContainer();
  596. this.liveRegion = $("<span>", {
  597. role: "status",
  598. "aria-live": "polite"
  599. })
  600. .addClass("select2-hidden-accessible")
  601. .appendTo(document.body);
  602. this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid()).replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
  603. this.containerSelector="#"+this.containerId;
  604. this.container.attr("id", this.containerId);
  605. // cache the body so future lookups are cheap
  606. this.body = thunk(function() { return opts.element.closest("body"); });
  607. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  608. this.container.attr("style", opts.element.attr("style"));
  609. this.container.css(evaluate(opts.containerCss));
  610. this.container.addClass(evaluate(opts.containerCssClass));
  611. this.elementTabIndex = this.opts.element.attr("tabindex");
  612. // swap container for the element
  613. this.opts.element
  614. .data("select2", this)
  615. .attr("tabindex", "-1")
  616. .before(this.container)
  617. .on("click.select2", killEvent); // do not leak click events
  618. this.container.data("select2", this);
  619. this.dropdown = this.container.find(".select2-drop");
  620. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  621. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  622. this.dropdown.data("select2", this);
  623. this.dropdown.on("click", killEvent);
  624. this.results = results = this.container.find(resultsSelector);
  625. this.search = search = this.container.find("input.select2-input");
  626. this.queryCount = 0;
  627. this.resultsPage = 0;
  628. this.context = null;
  629. // initialize the container
  630. this.initContainer();
  631. this.container.on("click", killEvent);
  632. installFilteredMouseMove(this.results);
  633. this.dropdown.on("mousemove-filtered touchstart touchmove touchend", resultsSelector, this.bind(this.highlightUnderEvent));
  634. installDebouncedScroll(80, this.results);
  635. this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));
  636. // do not propagate change event from the search field out of the component
  637. $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
  638. $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});
  639. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  640. if ($.fn.mousewheel) {
  641. results.mousewheel(function (e, delta, deltaX, deltaY) {
  642. var top = results.scrollTop();
  643. if (deltaY > 0 && top - deltaY <= 0) {
  644. results.scrollTop(0);
  645. killEvent(e);
  646. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  647. results.scrollTop(results.get(0).scrollHeight - results.height());
  648. killEvent(e);
  649. }
  650. });
  651. }
  652. installKeyUpChangeEvent(search);
  653. search.on("keyup-change input paste", this.bind(this.updateResults));
  654. search.on("focus", function () { search.addClass("select2-focused"); });
  655. search.on("blur", function () { search.removeClass("select2-focused");});
  656. this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
  657. if ($(e.target).closest(".select2-result-selectable").length > 0) {
  658. this.highlightUnderEvent(e);
  659. this.selectHighlighted(e);
  660. }
  661. }));
  662. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  663. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  664. // dom it will trigger the popup close, which is not what we want
  665. this.dropdown.on("click mouseup mousedown", function (e) { e.stopPropagation(); });
  666. this.nextSearchTerm = undefined;
  667. if ($.isFunction(this.opts.initSelection)) {
  668. // initialize selection based on the current value of the source element
  669. this.initSelection();
  670. // if the user has provided a function that can set selection based on the value of the source element
  671. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  672. this.monitorSource();
  673. }
  674. if (opts.maximumInputLength !== null) {
  675. this.search.attr("maxlength", opts.maximumInputLength);
  676. }
  677. var disabled = opts.element.prop("disabled");
  678. if (disabled === undefined) disabled = false;
  679. this.enable(!disabled);
  680. var readonly = opts.element.prop("readonly");
  681. if (readonly === undefined) readonly = false;
  682. this.readonly(readonly);
  683. // Calculate size of scrollbar
  684. scrollBarDimensions = scrollBarDimensions || measureScrollbar();
  685. this.autofocus = opts.element.prop("autofocus");
  686. opts.element.prop("autofocus", false);
  687. if (this.autofocus) this.focus();
  688. this.search.attr("placeholder", opts.searchInputPlaceholder);
  689. },
  690. // abstract
  691. destroy: function () {
  692. var element=this.opts.element, select2 = element.data("select2");
  693. this.close();
  694. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  695. if (select2 !== undefined) {
  696. select2.container.remove();
  697. select2.liveRegion.remove();
  698. select2.dropdown.remove();
  699. element
  700. .removeClass("select2-offscreen")
  701. .removeData("select2")
  702. .off(".select2")
  703. .prop("autofocus", this.autofocus || false);
  704. if (this.elementTabIndex) {
  705. element.attr({tabindex: this.elementTabIndex});
  706. } else {
  707. element.removeAttr("tabindex");
  708. }
  709. element.show();
  710. }
  711. },
  712. // abstract
  713. optionToData: function(element) {
  714. if (element.is("option")) {
  715. return {
  716. id:element.prop("value"),
  717. text:element.text(),
  718. element: element.get(),
  719. css: element.attr("class"),
  720. disabled: element.prop("disabled"),
  721. locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
  722. };
  723. } else if (element.is("optgroup")) {
  724. return {
  725. text:element.attr("label"),
  726. children:[],
  727. element: element.get(),
  728. css: element.attr("class")
  729. };
  730. }
  731. },
  732. // abstract
  733. prepareOpts: function (opts) {
  734. var element, select, idKey, ajaxUrl, self = this;
  735. element = opts.element;
  736. if (element.get(0).tagName.toLowerCase() === "select") {
  737. this.select = select = opts.element;
  738. }
  739. if (select) {
  740. // these options are not allowed when attached to a select because they are picked up off the element itself
  741. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  742. if (this in opts) {
  743. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  744. }
  745. });
  746. }
  747. opts = $.extend({}, {
  748. populateResults: function(container, results, query) {
  749. var populate, id=this.opts.id, liveRegion=this.liveRegion;
  750. populate=function(results, container, depth) {
  751. var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
  752. results = opts.sortResults(results, container, query);
  753. for (i = 0, l = results.length; i < l; i = i + 1) {
  754. result=results[i];
  755. disabled = (result.disabled === true);
  756. selectable = (!disabled) && (id(result) !== undefined);
  757. compound=result.children && result.children.length > 0;
  758. node=$("<li></li>");
  759. node.addClass("select2-results-dept-"+depth);
  760. node.addClass("select2-result");
  761. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  762. if (disabled) { node.addClass("select2-disabled"); }
  763. if (compound) { node.addClass("select2-result-with-children"); }
  764. node.addClass(self.opts.formatResultCssClass(result));
  765. node.attr("role", "presentation");
  766. label=$(document.createElement("div"));
  767. label.addClass("select2-result-label");
  768. label.attr("id", "select2-result-label-" + nextUid());
  769. label.attr("role", "option");
  770. formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
  771. if (formatted!==undefined) {
  772. label.html(formatted);
  773. }
  774. node.append(label);
  775. if (compound) {
  776. innerContainer=$("<ul></ul>");
  777. innerContainer.addClass("select2-result-sub");
  778. populate(result.children, innerContainer, depth+1);
  779. node.append(innerContainer);
  780. }
  781. node.data("select2-data", result);
  782. container.append(node);
  783. }
  784. liveRegion.text(opts.formatMatches(results.length));
  785. };
  786. populate(results, container, 0);
  787. }
  788. }, $.fn.select2.defaults, opts);
  789. if (typeof(opts.id) !== "function") {
  790. idKey = opts.id;
  791. opts.id = function (e) { return e[idKey]; };
  792. }
  793. if ($.isArray(opts.element.data("select2Tags"))) {
  794. if ("tags" in opts) {
  795. throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
  796. }
  797. opts.tags=opts.element.data("select2Tags");
  798. }
  799. if (select) {
  800. opts.query = this.bind(function (query) {
  801. var data = { results: [], more: false },
  802. term = query.term,
  803. children, placeholderOption, process;
  804. process=function(element, collection) {
  805. var group;
  806. if (element.is("option")) {
  807. if (query.matcher(term, element.text(), element)) {
  808. collection.push(self.optionToData(element));
  809. }
  810. } else if (element.is("optgroup")) {
  811. group=self.optionToData(element);
  812. element.children().each2(function(i, elm) { process(elm, group.children); });
  813. if (group.children.length>0) {
  814. collection.push(group);
  815. }
  816. }
  817. };
  818. children=element.children();
  819. // ignore the placeholder option if there is one
  820. if (this.getPlaceholder() !== undefined && children.length > 0) {
  821. placeholderOption = this.getPlaceholderOption();
  822. if (placeholderOption) {
  823. children=children.not(placeholderOption);
  824. }
  825. }
  826. children.each2(function(i, elm) { process(elm, data.results); });
  827. query.callback(data);
  828. });
  829. // this is needed because inside val() we construct choices from options and there id is hardcoded
  830. opts.id=function(e) { return e.id; };
  831. } else {
  832. if (!("query" in opts)) {
  833. if ("ajax" in opts) {
  834. ajaxUrl = opts.element.data("ajax-url");
  835. if (ajaxUrl && ajaxUrl.length > 0) {
  836. opts.ajax.url = ajaxUrl;
  837. }
  838. opts.query = ajax.call(opts.element, opts.ajax);
  839. } else if ("data" in opts) {
  840. opts.query = local(opts.data);
  841. } else if ("tags" in opts) {
  842. opts.query = tags(opts.tags);
  843. if (opts.createSearchChoice === undefined) {
  844. opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; };
  845. }
  846. if (opts.initSelection === undefined) {
  847. opts.initSelection = function (element, callback) {
  848. var data = [];
  849. $(splitVal(element.val(), opts.separator)).each(function () {
  850. var obj = { id: this, text: this },
  851. tags = opts.tags;
  852. if ($.isFunction(tags)) tags=tags();
  853. $(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } });
  854. data.push(obj);
  855. });
  856. callback(data);
  857. };
  858. }
  859. }
  860. }
  861. }
  862. if (typeof(opts.query) !== "function") {
  863. throw "query function not defined for Select2 " + opts.element.attr("id");
  864. }
  865. return opts;
  866. },
  867. /**
  868. * Monitor the original element for changes and update select2 accordingly
  869. */
  870. // abstract
  871. monitorSource: function () {
  872. var el = this.opts.element, sync, observer;
  873. el.on("change.select2", this.bind(function (e) {
  874. if (this.opts.element.data("select2-change-triggered") !== true) {
  875. this.initSelection();
  876. }
  877. }));
  878. sync = this.bind(function () {
  879. // sync enabled state
  880. var disabled = el.prop("disabled");
  881. if (disabled === undefined) disabled = false;
  882. this.enable(!disabled);
  883. var readonly = el.prop("readonly");
  884. if (readonly === undefined) readonly = false;
  885. this.readonly(readonly);
  886. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  887. this.container.addClass(evaluate(this.opts.containerCssClass));
  888. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  889. this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
  890. });
  891. // IE8-10
  892. el.on("propertychange.select2", sync);
  893. // hold onto a reference of the callback to work around a chromium bug
  894. if (this.mutationCallback === undefined) {
  895. this.mutationCallback = function (mutations) {
  896. mutations.forEach(sync);
  897. }
  898. }
  899. // safari, chrome, firefox, IE11
  900. observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver;
  901. if (observer !== undefined) {
  902. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  903. this.propertyObserver = new observer(this.mutationCallback);
  904. this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
  905. }
  906. },
  907. // abstract
  908. triggerSelect: function(data) {
  909. var evt = $.Event("select2-selecting", { val: this.id(data), object: data });
  910. this.opts.element.trigger(evt);
  911. return !evt.isDefaultPrevented();
  912. },
  913. /**
  914. * Triggers the change event on the source element
  915. */
  916. // abstract
  917. triggerChange: function (details) {
  918. details = details || {};
  919. details= $.extend({}, details, { type: "change", val: this.val() });
  920. // prevents recursive triggering
  921. this.opts.element.data("select2-change-triggered", true);
  922. this.opts.element.trigger(details);
  923. this.opts.element.data("select2-change-triggered", false);
  924. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  925. // so here we trigger the click event manually
  926. this.opts.element.click();
  927. // ValidationEngine ignores the change event and listens instead to blur
  928. // so here we trigger the blur event manually if so desired
  929. if (this.opts.blurOnChange)
  930. this.opts.element.blur();
  931. },
  932. //abstract
  933. isInterfaceEnabled: function()
  934. {
  935. return this.enabledInterface === true;
  936. },
  937. // abstract
  938. enableInterface: function() {
  939. var enabled = this._enabled && !this._readonly,
  940. disabled = !enabled;
  941. if (enabled === this.enabledInterface) return false;
  942. this.container.toggleClass("select2-container-disabled", disabled);
  943. this.close();
  944. this.enabledInterface = enabled;
  945. return true;
  946. },
  947. // abstract
  948. enable: function(enabled) {
  949. if (enabled === undefined) enabled = true;
  950. if (this._enabled === enabled) return;
  951. this._enabled = enabled;
  952. this.opts.element.prop("disabled", !enabled);
  953. this.enableInterface();
  954. },
  955. // abstract
  956. disable: function() {
  957. this.enable(false);
  958. },
  959. // abstract
  960. readonly: function(enabled) {
  961. if (enabled === undefined) enabled = false;
  962. if (this._readonly === enabled) return false;
  963. this._readonly = enabled;
  964. this.opts.element.prop("readonly", enabled);
  965. this.enableInterface();
  966. return true;
  967. },
  968. // abstract
  969. opened: function () {
  970. return this.container.hasClass("select2-dropdown-open");
  971. },
  972. // abstract
  973. positionDropdown: function() {
  974. var $dropdown = this.dropdown,
  975. offset = this.container.offset(),
  976. height = this.container.outerHeight(false),
  977. width = this.container.outerWidth(false),
  978. dropHeight = $dropdown.outerHeight(false),
  979. $window = $(window),
  980. windowWidth = $window.width(),
  981. windowHeight = $window.height(),
  982. viewPortRight = $window.scrollLeft() + windowWidth,
  983. viewportBottom = $window.scrollTop() + windowHeight,
  984. dropTop = offset.top + height,
  985. dropLeft = offset.left,
  986. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  987. enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
  988. dropWidth = $dropdown.outerWidth(false),
  989. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
  990. aboveNow = $dropdown.hasClass("select2-drop-above"),
  991. bodyOffset,
  992. above,
  993. changeDirection,
  994. css,
  995. resultsListNode;
  996. // always prefer the current above/below alignment, unless there is not enough room
  997. if (aboveNow) {
  998. above = true;
  999. if (!enoughRoomAbove && enoughRoomBelow) {
  1000. changeDirection = true;
  1001. above = false;
  1002. }
  1003. } else {
  1004. above = false;
  1005. if (!enoughRoomBelow && enoughRoomAbove) {
  1006. changeDirection = true;
  1007. above = true;
  1008. }
  1009. }
  1010. //if we are changing direction we need to get positions when dropdown is hidden;
  1011. if (changeDirection) {
  1012. $dropdown.hide();
  1013. offset = this.container.offset();
  1014. height = this.container.outerHeight(false);
  1015. width = this.container.outerWidth(false);
  1016. dropHeight = $dropdown.outerHeight(false);
  1017. viewPortRight = $window.scrollLeft() + windowWidth;
  1018. viewportBottom = $window.scrollTop() + windowHeight;
  1019. dropTop = offset.top + height;
  1020. dropLeft = offset.left;
  1021. dropWidth = $dropdown.outerWidth(false);
  1022. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
  1023. $dropdown.show();
  1024. }
  1025. if (this.opts.dropdownAutoWidth) {
  1026. resultsListNode = $('.select2-results', $dropdown)[0];
  1027. $dropdown.addClass('select2-drop-auto-width');
  1028. $dropdown.css('width', '');
  1029. // Add scrollbar width to dropdown if vertical scrollbar is present
  1030. dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
  1031. dropWidth > width ? width = dropWidth : dropWidth = width;
  1032. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
  1033. }
  1034. else {
  1035. this.container.removeClass('select2-drop-auto-width');
  1036. }
  1037. //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  1038. //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  1039. // fix positioning when body has an offset and is not position: static
  1040. if (this.body().css('position') !== 'static') {
  1041. bodyOffset = this.body().offset();
  1042. dropTop -= bodyOffset.top;
  1043. dropLeft -= bodyOffset.left;
  1044. }
  1045. if (!enoughRoomOnRight) {
  1046. dropLeft = offset.left + this.container.outerWidth(false) - dropWidth;
  1047. }
  1048. css = {
  1049. left: dropLeft,
  1050. width: width
  1051. };
  1052. if (above) {
  1053. css.top = offset.top - dropHeight;
  1054. css.bottom = 'auto';
  1055. this.container.addClass("select2-drop-above");
  1056. $dropdown.addClass("select2-drop-above");
  1057. }
  1058. else {
  1059. css.top = dropTop;
  1060. css.bottom = 'auto';
  1061. this.container.removeClass("select2-drop-above");
  1062. $dropdown.removeClass("select2-drop-above");
  1063. }
  1064. css = $.extend(css, evaluate(this.opts.dropdownCss));
  1065. $dropdown.css(css);
  1066. },
  1067. // abstract
  1068. shouldOpen: function() {
  1069. var event;
  1070. if (this.opened()) return false;
  1071. if (this._enabled === false || this._readonly === true) return false;
  1072. event = $.Event("select2-opening");
  1073. this.opts.element.trigger(event);
  1074. return !event.isDefaultPrevented();
  1075. },
  1076. // abstract
  1077. clearDropdownAlignmentPreference: function() {
  1078. // clear the classes used to figure out the preference of where the dropdown should be opened
  1079. this.container.removeClass("select2-drop-above");
  1080. this.dropdown.removeClass("select2-drop-above");
  1081. },
  1082. /**
  1083. * Opens the dropdown
  1084. *
  1085. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  1086. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  1087. */
  1088. // abstract
  1089. open: function () {
  1090. if (!this.shouldOpen()) return false;
  1091. this.opening();
  1092. return true;
  1093. },
  1094. /**
  1095. * Performs the opening of the dropdown
  1096. */
  1097. // abstract
  1098. opening: function() {
  1099. var cid = this.containerId,
  1100. scroll = "scroll." + cid,
  1101. resize = "resize."+cid,
  1102. orient = "orientationchange."+cid,
  1103. mask;
  1104. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  1105. this.clearDropdownAlignmentPreference();
  1106. if(this.dropdown[0] !== this.body().children().last()[0]) {
  1107. this.dropdown.detach().appendTo(this.body());
  1108. }
  1109. // create the dropdown mask if doesn't already exist
  1110. mask = $("#select2-drop-mask");
  1111. if (mask.length == 0) {
  1112. mask = $(document.createElement("div"));
  1113. mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
  1114. mask.hide();
  1115. mask.appendTo(this.body());
  1116. mask.on("mousedown touchstart click", function (e) {
  1117. // Prevent IE from generating a click event on the body
  1118. reinsertElement(mask);
  1119. var dropdown = $("#select2-drop"), self;
  1120. if (dropdown.length > 0) {
  1121. self=dropdown.data("select2");
  1122. if (self.opts.selectOnBlur) {
  1123. self.selectHighlighted({noFocus: true});
  1124. }
  1125. self.close({focus:true});
  1126. e.preventDefault();
  1127. e.stopPropagation();
  1128. }
  1129. });
  1130. }
  1131. // ensure the mask is always right before the dropdown
  1132. if (this.dropdown.prev()[0] !== mask[0]) {
  1133. this.dropdown.before(mask);
  1134. }
  1135. // move the global id to the correct dropdown
  1136. $("#select2-drop").removeAttr("id");
  1137. this.dropdown.attr("id", "select2-drop");
  1138. // show the elements
  1139. mask.show();
  1140. this.positionDropdown();
  1141. this.dropdown.show();
  1142. this.positionDropdown();
  1143. this.dropdown.addClass("select2-drop-active");
  1144. // attach listeners to events that can change the position of the container and thus require
  1145. // the position of the dropdown to be updated as well so it does not come unglued from the container
  1146. var that = this;
  1147. this.container.parents().add(window).each(function () {
  1148. $(this).on(resize+" "+scroll+" "+orient, function (e) {
  1149. that.positionDropdown();
  1150. });
  1151. });
  1152. },
  1153. // abstract
  1154. close: function () {
  1155. if (!this.opened()) return;
  1156. var cid = this.containerId,
  1157. scroll = "scroll." + cid,
  1158. resize = "resize."+cid,
  1159. orient = "orientationchange."+cid;
  1160. // unbind event listeners
  1161. this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });
  1162. this.clearDropdownAlignmentPreference();
  1163. $("#select2-drop-mask").hide();
  1164. this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
  1165. this.dropdown.hide();
  1166. this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
  1167. this.results.empty();
  1168. this.clearSearch();
  1169. this.search.removeClass("select2-active");
  1170. this.opts.element.trigger($.Event("select2-close"));
  1171. },
  1172. /**
  1173. * Opens control, sets input value, and updates results.
  1174. */
  1175. // abstract
  1176. externalSearch: function (term) {
  1177. this.open();
  1178. this.search.val(term);
  1179. this.updateResults(false);
  1180. },
  1181. // abstract
  1182. clearSearch: function () {
  1183. },
  1184. //abstract
  1185. getMaximumSelectionSize: function() {
  1186. return evaluate(this.opts.maximumSelectionSize);
  1187. },
  1188. // abstract
  1189. ensureHighlightVisible: function () {
  1190. var results = this.results, children, index, child, hb, rb, y, more;
  1191. index = this.highlight();
  1192. if (index < 0) return;
  1193. if (index == 0) {
  1194. // if the first element is highlighted scroll all the way to the top,
  1195. // that way any unselectable headers above it will also be scrolled
  1196. // into view
  1197. results.scrollTop(0);
  1198. return;
  1199. }
  1200. children = this.findHighlightableChoices().find('.select2-result-label');
  1201. child = $(children[index]);
  1202. hb = child.offset().top + child.outerHeight(true);
  1203. // if this is the last child lets also make sure select2-more-results is visible
  1204. if (index === children.length - 1) {
  1205. more = results.find("li.select2-more-results");
  1206. if (more.length > 0) {
  1207. hb = more.offset().top + more.outerHeight(true);
  1208. }
  1209. }
  1210. rb = results.offset().top + results.outerHeight(true);
  1211. if (hb > rb) {
  1212. results.scrollTop(results.scrollTop() + (hb - rb));
  1213. }
  1214. y = child.offset().top - results.offset().top;
  1215. // make sure the top of the element is visible
  1216. if (y < 0 && child.css('display') != 'none' ) {
  1217. results.scrollTop(results.scrollTop() + y); // y is negative
  1218. }
  1219. },
  1220. // abstract
  1221. findHighlightableChoices: function() {
  1222. return this.results.find(".select2-result-selectable:not(.select2-disabled, .select2-selected)");
  1223. },
  1224. // abstract
  1225. moveHighlight: function (delta) {
  1226. var choices = this.findHighlightableChoices(),
  1227. index = this.highlight();
  1228. while (index > -1 && index < choices.length) {
  1229. index += delta;
  1230. var choice = $(choices[index]);
  1231. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
  1232. this.highlight(index);
  1233. break;
  1234. }
  1235. }
  1236. },
  1237. // abstract
  1238. highlight: function (index) {
  1239. var choices = this.findHighlightableChoices(),
  1240. choice,
  1241. data;
  1242. if (arguments.length === 0) {
  1243. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  1244. }
  1245. if (index >= choices.length) index = choices.length - 1;
  1246. if (index < 0) index = 0;
  1247. this.removeHighlight();
  1248. choice = $(choices[index]);
  1249. choice.addClass("select2-highlighted");
  1250. // ensure assistive technology can determine the active choice
  1251. this.search.attr("aria-activedescendant", choice.find(".select2-result-label").attr("id"));
  1252. this.ensureHighlightVisible();
  1253. this.liveRegion.text(choice.text());
  1254. data = choice.data("select2-data");
  1255. if (data) {
  1256. this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
  1257. }
  1258. },
  1259. removeHighlight: function() {
  1260. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1261. },
  1262. // abstract
  1263. countSelectableResults: function() {
  1264. return this.findHighlightableChoices().length;
  1265. },
  1266. // abstract
  1267. highlightUnderEvent: function (event) {
  1268. var el = $(event.target).closest(".select2-result-selectable");
  1269. if (el.length > 0 && !el.is(".select2-highlighted")) {
  1270. var choices = this.findHighlightableChoices();
  1271. this.highlight(choices.index(el));
  1272. } else if (el.length == 0) {
  1273. // if we are over an unselectable item remove all highlights
  1274. this.removeHighlight();
  1275. }
  1276. },
  1277. // abstract
  1278. loadMoreIfNeeded: function () {
  1279. var results = this.results,
  1280. more = results.find("li.select2-more-results"),
  1281. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  1282. page = this.resultsPage + 1,
  1283. self=this,
  1284. term=this.search.val(),
  1285. context=this.context;
  1286. if (more.length === 0) return;
  1287. below = more.offset().top - results.offset().top - results.height();
  1288. if (below <= this.opts.loadMorePadding) {
  1289. more.addClass("select2-active");
  1290. this.opts.query({
  1291. element: this.opts.element,
  1292. term: term,
  1293. page: page,
  1294. context: context,
  1295. matcher: this.opts.matcher,
  1296. callback: this.bind(function (data) {
  1297. // ignore a response if the select2 has been closed before it was received
  1298. if (!self.opened()) return;
  1299. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  1300. self.postprocessResults(data, false, false);
  1301. if (data.more===true) {
  1302. more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
  1303. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1304. } else {
  1305. more.remove();
  1306. }
  1307. self.positionDropdown();
  1308. self.resultsPage = page;
  1309. self.context = data.context;
  1310. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1311. })});
  1312. }
  1313. },
  1314. /**
  1315. * Default tokenizer function which does nothing
  1316. */
  1317. tokenize: function() {
  1318. },
  1319. /**
  1320. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  1321. */
  1322. // abstract
  1323. updateResults: function (initial) {
  1324. var search = this.search,
  1325. results = this.results,
  1326. opts = this.opts,
  1327. data,
  1328. self = this,
  1329. input,
  1330. term = search.val(),
  1331. lastTerm = $.data(this.container, "select2-last-term"),
  1332. // sequence number used to drop out-of-order responses
  1333. queryNumber;
  1334. // prevent duplicate queries against the same term
  1335. if (initial !== true && lastTerm && equal(term, lastTerm)) return;
  1336. $.data(this.container, "select2-last-term", term);
  1337. // if the search is currently hidden we do not alter the results
  1338. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  1339. return;
  1340. }
  1341. function postRender() {
  1342. search.removeClass("select2-active");
  1343. self.positionDropdown();
  1344. if (results.find('.select2-no-results,.select2-selection-limit,.select2-searching').length) {
  1345. self.liveRegion.text(results.text());
  1346. }
  1347. else {
  1348. self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable').length));
  1349. }
  1350. }
  1351. function render(html) {
  1352. results.html(html);
  1353. postRender();
  1354. }
  1355. queryNumber = ++this.queryCount;
  1356. var maxSelSize = this.getMaximumSelectionSize();
  1357. if (maxSelSize >=1) {
  1358. data = this.data();
  1359. if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  1360. render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>");
  1361. return;
  1362. }
  1363. }
  1364. if (search.val().length < opts.minimumInputLength) {
  1365. if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  1366. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  1367. } else {
  1368. render("");
  1369. }
  1370. if (initial && this.showSearch) this.showSearch(true);
  1371. return;
  1372. }
  1373. if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
  1374. if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
  1375. render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>");
  1376. } else {
  1377. render("");
  1378. }
  1379. return;
  1380. }
  1381. if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
  1382. render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
  1383. }
  1384. search.addClass("select2-active");
  1385. this.removeHighlight();
  1386. // give the tokenizer a chance to pre-process the input
  1387. input = this.tokenize();
  1388. if (input != undefined && input != null) {
  1389. search.val(input);
  1390. }
  1391. this.resultsPage = 1;
  1392. opts.query({
  1393. element: opts.element,
  1394. term: search.val(),
  1395. page: this.resultsPage,
  1396. context: null,
  1397. matcher: opts.matcher,
  1398. callback: this.bind(function (data) {
  1399. var def; // default choice
  1400. // ignore old responses
  1401. if (queryNumber != this.queryCount) {
  1402. return;
  1403. }
  1404. // ignore a response if the select2 has been closed before it was received
  1405. if (!this.opened()) {
  1406. this.search.removeClass("select2-active");
  1407. return;
  1408. }
  1409. // save context, if any
  1410. this.context = (data.context===undefined) ? null : data.context;
  1411. // create a default choice and prepend it to the list
  1412. if (this.opts.createSearchChoice && search.val() !== "") {
  1413. def = this.opts.createSearchChoice.call(self, search.val(), data.results);
  1414. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  1415. if ($(data.results).filter(
  1416. function () {
  1417. return equal(self.id(this), self.id(def));
  1418. }).length === 0) {
  1419. data.results.unshift(def);
  1420. }
  1421. }
  1422. }
  1423. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  1424. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  1425. return;
  1426. }
  1427. results.empty();
  1428. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  1429. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  1430. results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
  1431. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1432. }
  1433. this.postprocessResults(data, initial);
  1434. postRender();
  1435. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1436. })});
  1437. },
  1438. // abstract
  1439. cancel: function () {
  1440. this.close();
  1441. },
  1442. // abstract
  1443. blur: function () {
  1444. // if selectOnBlur == true, select the currently highlighted option
  1445. if (this.opts.selectOnBlur)
  1446. this.selectHighlighted({noFocus: true});
  1447. this.close();
  1448. this.container.removeClass("select2-container-active");
  1449. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  1450. if (this.search[0] === document.activeElement) { this.search.blur(); }
  1451. this.clearSearch();
  1452. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1453. },
  1454. // abstract
  1455. focusSearch: function () {
  1456. focus(this.search);
  1457. },
  1458. // abstract
  1459. selectHighlighted: function (options) {
  1460. var index=this.highlight(),
  1461. highlighted=this.results.find(".select2-highlighted"),
  1462. data = highlighted.closest('.select2-result').data("select2-data");
  1463. if (data) {
  1464. this.highlight(index);
  1465. this.onSelect(data, options);
  1466. } else if (options && options.noFocus) {
  1467. this.close();
  1468. }
  1469. },
  1470. // abstract
  1471. getPlaceholder: function () {
  1472. var placeholderOption;
  1473. return this.opts.element.attr("placeholder") ||
  1474. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1475. this.opts.element.data("placeholder") ||
  1476. this.opts.placeholder ||
  1477. ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
  1478. },
  1479. // abstract
  1480. getPlaceholderOption: function() {
  1481. if (this.select) {
  1482. var firstOption = this.select.children('option').first();
  1483. if (this.opts.placeholderOption !== undefined ) {
  1484. //Determine the placeholder option based on the specified placeholderOption setting
  1485. return (this.opts.placeholderOption === "first" && firstOption) ||
  1486. (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
  1487. } else if (firstOption.text() === "" && firstOption.val() === "") {
  1488. //No explicit placeholder option specified, use the first if it's blank
  1489. return firstOption;
  1490. }
  1491. }
  1492. },
  1493. /**
  1494. * Get the desired width for the container element. This is
  1495. * derived first from option `width` passed to select2, then
  1496. * the inline 'style' on the original element, and finally
  1497. * falls back to the jQuery calculated element width.
  1498. */
  1499. // abstract
  1500. initContainerWidth: function () {
  1501. function resolveContainerWidth() {
  1502. var style, attrs, matches, i, l, attr;
  1503. if (this.opts.width === "off") {
  1504. return null;
  1505. } else if (this.opts.width === "element"){
  1506. return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
  1507. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1508. // check if there is inline style on the element that contains width
  1509. style = this.opts.element.attr('style');
  1510. if (style !== undefined) {
  1511. attrs = style.split(';');
  1512. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1513. attr = attrs[i].replace(/\s/g, '');
  1514. matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
  1515. if (matches !== null && matches.length >= 1)
  1516. return matches[1];
  1517. }
  1518. }
  1519. if (this.opts.width === "resolve") {
  1520. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1521. // when attached to input type=hidden or elements hidden via css
  1522. style = this.opts.element.css('width');
  1523. if (style.indexOf("%") > 0) return style;
  1524. // finally, fallback on the calculated width of the element
  1525. return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
  1526. }
  1527. return null;
  1528. } else if ($.isFunction(this.opts.width)) {
  1529. return this.opts.width();
  1530. } else {
  1531. return this.opts.width;
  1532. }
  1533. };
  1534. var width = resolveContainerWidth.call(this);
  1535. if (width !== null) {
  1536. this.container.css("width", width);
  1537. }
  1538. }
  1539. });
  1540. SingleSelect2 = clazz(AbstractSelect2, {
  1541. // single
  1542. createContainer: function () {
  1543. var container = $(document.createElement("div")).attr({
  1544. "class": "select2-container"
  1545. }).html([
  1546. "<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>",
  1547. " <span class='select2-chosen'>&nbsp;</span><abbr class='select2-search-choice-close'></abbr>",
  1548. " <span class='select2-arrow' role='presentation'><b role='presentation'></b></span>",
  1549. "</a>",
  1550. "<label for='' class='select2-offscreen'></label>",
  1551. "<input class='select2-focusser select2-offscreen' type='text' aria-haspopup='true' role='button' />",
  1552. "<div class='select2-drop select2-display-none'>",
  1553. " <div class='select2-search'>",
  1554. " <label for='' class='select2-offscreen'></label>",
  1555. " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' role='combobox' aria-expanded='true'",
  1556. " aria-autocomplete='list' />",
  1557. " </div>",
  1558. " <ul class='select2-results' role='listbox'>",
  1559. " </ul>",
  1560. "</div>"].join(""));
  1561. return container;
  1562. },
  1563. // single
  1564. enableInterface: function() {
  1565. if (this.parent.enableInterface.apply(this, arguments)) {
  1566. this.focusser.prop("disabled", !this.isInterfaceEnabled());
  1567. }
  1568. },
  1569. // single
  1570. opening: function () {
  1571. var el, range, len;
  1572. if (this.opts.minimumResultsForSearch >= 0) {
  1573. this.showSearch(true);
  1574. }
  1575. this.parent.opening.apply(this, arguments);
  1576. if (this.showSearchInput !== false) {
  1577. // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
  1578. // all other browsers handle this just fine
  1579. this.search.val(this.focusser.val());
  1580. }
  1581. this.search.focus();
  1582. // move the cursor to the end after focussing, otherwise it will be at the beginning and
  1583. // new text will appear *before* focusser.val()
  1584. el = this.search.get(0);
  1585. if (el.createTextRange) {
  1586. range = el.createTextRange();
  1587. range.collapse(false);
  1588. range.select();
  1589. } else if (el.setSelectionRange) {
  1590. len = this.search.val().length;
  1591. el.setSelectionRange(len, len);
  1592. }
  1593. // initializes search's value with nextSearchTerm (if defined by user)
  1594. // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
  1595. if(this.search.val() === "") {
  1596. if(this.nextSearchTerm != undefined){
  1597. this.search.val(this.nextSearchTerm);
  1598. this.search.select();
  1599. }
  1600. }
  1601. this.focusser.prop("disabled", true).val("");
  1602. this.updateResults(true);
  1603. this.opts.element.trigger($.Event("select2-open"));
  1604. },
  1605. // single
  1606. close: function (params) {
  1607. if (!this.opened()) return;
  1608. this.parent.close.apply(this, arguments);
  1609. params = params || {focus: true};
  1610. this.focusser.prop("disabled", false);
  1611. if (params.focus) {
  1612. this.focusser.focus();
  1613. }
  1614. },
  1615. // single
  1616. focus: function () {
  1617. if (this.opened()) {
  1618. this.close();
  1619. } else {
  1620. this.focusser.prop("disabled", false);
  1621. this.focusser.focus();
  1622. }
  1623. },
  1624. // single
  1625. isFocused: function () {
  1626. return this.container.hasClass("select2-container-active");
  1627. },
  1628. // single
  1629. cancel: function () {
  1630. this.parent.cancel.apply(this, arguments);
  1631. this.focusser.prop("disabled", false);
  1632. this.focusser.focus();
  1633. },
  1634. // single
  1635. destroy: function() {
  1636. $("label[for='" + this.focusser.attr('id') + "']")
  1637. .attr('for', this.opts.element.attr("id"));
  1638. this.parent.destroy.apply(this, arguments);
  1639. },
  1640. // single
  1641. initContainer: function () {
  1642. var selection,
  1643. container = this.container,
  1644. dropdown = this.dropdown,
  1645. idSuffix = nextUid(),
  1646. elementLabel;
  1647. if (this.opts.minimumResultsForSearch < 0) {
  1648. this.showSearch(false);
  1649. } else {
  1650. this.showSearch(true);
  1651. }
  1652. this.selection = selection = container.find(".select2-choice");
  1653. this.focusser = container.find(".select2-focusser");
  1654. // add aria associations
  1655. selection.find(".select2-chosen").attr("id", "select2-chosen-"+idSuffix);
  1656. this.focusser.attr("aria-labelledby", "select2-chosen-"+idSuffix);
  1657. this.results.attr("id", "select2-results-"+idSuffix);
  1658. this.search.attr("aria-owns", "select2-results-"+idSuffix);
  1659. // rewrite labels from original element to focusser
  1660. this.focusser.attr("id", "s2id_autogen"+idSuffix);
  1661. elementLabel = $("label[for='" + this.opts.element.attr("id") + "']");
  1662. this.focusser.prev()
  1663. .text(elementLabel.text())
  1664. .attr('for', this.focusser.attr('id'));
  1665. // Ensure the original element retains an accessible name
  1666. var originalTitle = this.opts.element.attr("title");
  1667. this.opts.element.attr("title", (originalTitle || elementLabel.text()));
  1668. this.focusser.attr("tabindex", this.elementTabIndex);
  1669. // write label for search field using the label from the focusser element
  1670. this.search.attr("id", this.focusser.attr('id') + '_search');
  1671. this.search.prev()
  1672. .text($("label[for='" + this.focusser.attr('id') + "']").text())
  1673. .attr('for', this.search.attr('id'));
  1674. this.search.on("keydown", this.bind(function (e) {
  1675. if (!this.isInterfaceEnabled()) return;
  1676. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1677. // prevent the page from scrolling
  1678. killEvent(e);
  1679. return;
  1680. }
  1681. switch (e.which) {
  1682. case KEY.UP:
  1683. case KEY.DOWN:
  1684. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1685. killEvent(e);
  1686. return;
  1687. case KEY.ENTER:
  1688. this.selectHighlighted();
  1689. killEvent(e);
  1690. return;
  1691. case KEY.TAB:
  1692. this.selectHighlighted({noFocus: true});
  1693. return;
  1694. case KEY.ESC:
  1695. this.cancel(e);
  1696. killEvent(e);
  1697. return;
  1698. }
  1699. }));
  1700. this.search.on("blur", this.bind(function(e) {
  1701. // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
  1702. // without this the search field loses focus which is annoying
  1703. if (document.activeElement === this.body().get(0)) {
  1704. window.setTimeout(this.bind(function() {
  1705. if (this.opened()) {
  1706. this.search.focus();
  1707. }
  1708. }), 0);
  1709. }
  1710. }));
  1711. this.focusser.on("keydown", this.bind(function (e) {
  1712. if (!this.isInterfaceEnabled()) return;
  1713. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1714. return;
  1715. }
  1716. if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
  1717. killEvent(e);
  1718. return;
  1719. }
  1720. if (e.which == KEY.DOWN || e.which == KEY.UP
  1721. || (e.which == KEY.ENTER && this.opts.openOnEnter)) {
  1722. if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;
  1723. this.open();
  1724. killEvent(e);
  1725. return;
  1726. }
  1727. if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
  1728. if (this.opts.allowClear) {
  1729. this.clear();
  1730. }
  1731. killEvent(e);
  1732. return;
  1733. }
  1734. }));
  1735. installKeyUpChangeEvent(this.focusser);
  1736. this.focusser.on("keyup-change input", this.bind(function(e) {
  1737. if (this.opts.minimumResultsForSearch >= 0) {
  1738. e.stopPropagation();
  1739. if (this.opened()) return;
  1740. this.open();
  1741. }
  1742. }));
  1743. selection.on("mousedown touchstart", "abbr", this.bind(function (e) {
  1744. if (!this.isInterfaceEnabled()) return;
  1745. this.clear();
  1746. killEventImmediately(e);
  1747. this.close();
  1748. this.selection.focus();
  1749. }));
  1750. selection.on("mousedown touchstart", this.bind(function (e) {
  1751. // Prevent IE from generating a click event on the body
  1752. reinsertElement(selection);
  1753. if (!this.container.hasClass("select2-container-active")) {
  1754. this.opts.element.trigger($.Event("select2-focus"));
  1755. }
  1756. if (this.opened()) {
  1757. this.close();
  1758. } else if (this.isInterfaceEnabled()) {
  1759. this.open();
  1760. }
  1761. killEvent(e);
  1762. }));
  1763. dropdown.on("mousedown touchstart", this.bind(function() { this.search.focus(); }));
  1764. selection.on("focus", this.bind(function(e) {
  1765. killEvent(e);
  1766. }));
  1767. this.focusser.on("focus", this.bind(function(){
  1768. if (!this.container.hasClass("select2-container-active")) {
  1769. this.opts.element.trigger($.Event("select2-focus"));
  1770. }
  1771. this.container.addClass("select2-container-active");
  1772. })).on("blur", this.bind(function() {
  1773. if (!this.opened()) {
  1774. this.container.removeClass("select2-container-active");
  1775. this.opts.element.trigger($.Event("select2-blur"));
  1776. }
  1777. }));
  1778. this.search.on("focus", this.bind(function(){
  1779. if (!this.container.hasClass("select2-container-active")) {
  1780. this.opts.element.trigger($.Event("select2-focus"));
  1781. }
  1782. this.container.addClass("select2-container-active");
  1783. }));
  1784. this.initContainerWidth();
  1785. this.opts.element.addClass("select2-offscreen");
  1786. this.setPlaceholder();
  1787. },
  1788. // single
  1789. clear: function(triggerChange) {
  1790. var data=this.selection.data("select2-data");
  1791. if (data) { // guard against queued quick consecutive clicks
  1792. var evt = $.Event("select2-clearing");
  1793. this.opts.element.trigger(evt);
  1794. if (evt.isDefaultPrevented()) {
  1795. return;
  1796. }
  1797. var placeholderOption = this.getPlaceholderOption();
  1798. this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
  1799. this.selection.find(".select2-chosen").empty();
  1800. this.selection.removeData("select2-data");
  1801. this.setPlaceholder();
  1802. if (triggerChange !== false){
  1803. this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
  1804. this.triggerChange({removed:data});
  1805. }
  1806. }
  1807. },
  1808. /**
  1809. * Sets selection based on source element's value
  1810. */
  1811. // single
  1812. initSelection: function () {
  1813. var selected;
  1814. if (this.isPlaceholderOptionSelected()) {
  1815. this.updateSelection(null);
  1816. this.close();
  1817. this.setPlaceholder();
  1818. } else {
  1819. var self = this;
  1820. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1821. if (selected !== undefined && selected !== null) {
  1822. self.updateSelection(selected);
  1823. self.close();
  1824. self.setPlaceholder();
  1825. self.nextSearchTerm = self.opts.nextSearchTerm(selected, self.search.val());
  1826. }
  1827. });
  1828. }
  1829. },
  1830. isPlaceholderOptionSelected: function() {
  1831. var placeholderOption;
  1832. if (!this.getPlaceholder()) return false; // no placeholder specified so no option should be considered
  1833. return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected"))
  1834. || (this.opts.element.val() === "")
  1835. || (this.opts.element.val() === undefined)
  1836. || (this.opts.element.val() === null);
  1837. },
  1838. // single
  1839. prepareOpts: function () {
  1840. var opts = this.parent.prepareOpts.apply(this, arguments),
  1841. self=this;
  1842. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1843. // install the selection initializer
  1844. opts.initSelection = function (element, callback) {
  1845. var selected = element.find("option").filter(function() { return this.selected });
  1846. // a single select box always has a value, no need to null check 'selected'
  1847. callback(self.optionToData(selected));
  1848. };
  1849. } else if ("data" in opts) {
  1850. // install default initSelection when applied to hidden input and data is local
  1851. opts.initSelection = opts.initSelection || function (element, callback) {
  1852. var id = element.val();
  1853. //search in data by id, storing the actual matching item
  1854. var match = null;
  1855. opts.query({
  1856. matcher: function(term, text, el){
  1857. var is_match = equal(id, opts.id(el));
  1858. if (is_match) {
  1859. match = el;
  1860. }
  1861. return is_match;
  1862. },
  1863. callback: !$.isFunction(callback) ? $.noop : function() {
  1864. callback(match);
  1865. }
  1866. });
  1867. };
  1868. }
  1869. return opts;
  1870. },
  1871. // single
  1872. getPlaceholder: function() {
  1873. // if a placeholder is specified on a single select without a valid placeholder option ignore it
  1874. if (this.select) {
  1875. if (this.getPlaceholderOption() === undefined) {
  1876. return undefined;
  1877. }
  1878. }
  1879. return this.parent.getPlaceholder.apply(this, arguments);
  1880. },
  1881. // single
  1882. setPlaceholder: function () {
  1883. var placeholder = this.getPlaceholder();
  1884. if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {
  1885. // check for a placeholder option if attached to a select
  1886. if (this.select && this.getPlaceholderOption() === undefined) return;
  1887. this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));
  1888. this.selection.addClass("select2-default");
  1889. this.container.removeClass("select2-allowclear");
  1890. }
  1891. },
  1892. // single
  1893. postprocessResults: function (data, initial, noHighlightUpdate) {
  1894. var selected = 0, self = this, showSearchInput = true;
  1895. // find the selected element in the result list
  1896. this.findHighlightableChoices().each2(function (i, elm) {
  1897. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1898. selected = i;
  1899. return false;
  1900. }
  1901. });
  1902. // and highlight it
  1903. if (noHighlightUpdate !== false) {
  1904. if (initial === true && selected >= 0) {
  1905. this.highlight(selected);
  1906. } else {
  1907. this.highlight(0);
  1908. }
  1909. }
  1910. // hide the search box if this is the first we got the results and there are enough of them for search
  1911. if (initial === true) {
  1912. var min = this.opts.minimumResultsForSearch;
  1913. if (min >= 0) {
  1914. this.showSearch(countResults(data.results) >= min);
  1915. }
  1916. }
  1917. },
  1918. // single
  1919. showSearch: function(showSearchInput) {
  1920. if (this.showSearchInput === showSearchInput) return;
  1921. this.showSearchInput = showSearchInput;
  1922. this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
  1923. this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
  1924. //add "select2-with-searchbox" to the container if search box is shown
  1925. $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
  1926. },
  1927. // single
  1928. onSelect: function (data, options) {
  1929. if (!this.triggerSelect(data)) { return; }
  1930. var old = this.opts.element.val(),
  1931. oldData = this.data();
  1932. this.opts.element.val(this.id(data));
  1933. this.updateSelection(data);
  1934. this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
  1935. this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
  1936. this.close();
  1937. if (!options || !options.noFocus)
  1938. this.focusser.focus();
  1939. if (!equal(old, this.id(data))) { this.triggerChange({added:data,removed:oldData}); }
  1940. },
  1941. // single
  1942. updateSelection: function (data) {
  1943. var container=this.selection.find(".select2-chosen"), formatted, cssClass;
  1944. this.selection.data("select2-data", data);
  1945. container.empty();
  1946. if (data !== null) {
  1947. formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
  1948. }
  1949. if (formatted !== undefined) {
  1950. container.append(formatted);
  1951. }
  1952. cssClass=this.opts.formatSelectionCssClass(data, container);
  1953. if (cssClass !== undefined) {
  1954. container.addClass(cssClass);
  1955. }
  1956. this.selection.removeClass("select2-default");
  1957. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1958. this.container.addClass("select2-allowclear");
  1959. }
  1960. },
  1961. // single
  1962. val: function () {
  1963. var val,
  1964. triggerChange = false,
  1965. data = null,
  1966. self = this,
  1967. oldData = this.data();
  1968. if (arguments.length === 0) {
  1969. return this.opts.element.val();
  1970. }
  1971. val = arguments[0];
  1972. if (arguments.length > 1) {
  1973. triggerChange = arguments[1];
  1974. }
  1975. if (this.select) {
  1976. this.select
  1977. .val(val)
  1978. .find("option").filter(function() { return this.selected }).each2(function (i, elm) {
  1979. data = self.optionToData(elm);
  1980. return false;
  1981. });
  1982. this.updateSelection(data);
  1983. this.setPlaceholder();
  1984. if (triggerChange) {
  1985. this.triggerChange({added: data, removed:oldData});
  1986. }
  1987. } else {
  1988. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  1989. if (!val && val !== 0) {
  1990. this.clear(triggerChange);
  1991. return;
  1992. }
  1993. if (this.opts.initSelection === undefined) {
  1994. throw new Error("cannot call val() if initSelection() is not defined");
  1995. }
  1996. this.opts.element.val(val);
  1997. this.opts.initSelection(this.opts.element, function(data){
  1998. self.opts.element.val(!data ? "" : self.id(data));
  1999. self.updateSelection(data);
  2000. self.setPlaceholder();
  2001. if (triggerChange) {
  2002. self.triggerChange({added: data, removed:oldData});
  2003. }
  2004. });
  2005. }
  2006. },
  2007. // single
  2008. clearSearch: function () {
  2009. this.search.val("");
  2010. this.focusser.val("");
  2011. },
  2012. // single
  2013. data: function(value) {
  2014. var data,
  2015. triggerChange = false;
  2016. if (arguments.length === 0) {
  2017. data = this.selection.data("select2-data");
  2018. if (data == undefined) data = null;
  2019. return data;
  2020. } else {
  2021. if (arguments.length > 1) {
  2022. triggerChange = arguments[1];
  2023. }
  2024. if (!value) {
  2025. this.clear(triggerChange);
  2026. } else {
  2027. data = this.data();
  2028. this.opts.element.val(!value ? "" : this.id(value));
  2029. this.updateSelection(value);
  2030. if (triggerChange) {
  2031. this.triggerChange({added: value, removed:data});
  2032. }
  2033. }
  2034. }
  2035. }
  2036. });
  2037. MultiSelect2 = clazz(AbstractSelect2, {
  2038. // multi
  2039. createContainer: function () {
  2040. var container = $(document.createElement("div")).attr({
  2041. "class": "select2-container select2-container-multi"
  2042. }).html([
  2043. "<ul class='select2-choices'>",
  2044. " <li class='select2-search-field'>",
  2045. " <label for='' class='select2-offscreen'></label>",
  2046. " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>",
  2047. " </li>",
  2048. "</ul>",
  2049. "<div class='select2-drop select2-drop-multi select2-display-none'>",
  2050. " <ul class='select2-results'>",
  2051. " </ul>",
  2052. "</div>"].join(""));
  2053. return container;
  2054. },
  2055. // multi
  2056. prepareOpts: function () {
  2057. var opts = this.parent.prepareOpts.apply(this, arguments),
  2058. self=this;
  2059. // TODO validate placeholder is a string if specified
  2060. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2061. // install the selection initializer
  2062. opts.initSelection = function (element, callback) {
  2063. var data = [];
  2064. element.find("option").filter(function() { return this.selected }).each2(function (i, elm) {
  2065. data.push(self.optionToData(elm));
  2066. });
  2067. callback(data);
  2068. };
  2069. } else if ("data" in opts) {
  2070. // install default initSelection when applied to hidden input and data is local
  2071. opts.initSelection = opts.initSelection || function (element, callback) {
  2072. var ids = splitVal(element.val(), opts.separator);
  2073. //search in data by array of ids, storing matching items in a list
  2074. var matches = [];
  2075. opts.query({
  2076. matcher: function(term, text, el){
  2077. var is_match = $.grep(ids, function(id) {
  2078. return equal(id, opts.id(el));
  2079. }).length;
  2080. if (is_match) {
  2081. matches.push(el);
  2082. }
  2083. return is_match;
  2084. },
  2085. callback: !$.isFunction(callback) ? $.noop : function() {
  2086. // reorder matches based on the order they appear in the ids array because right now
  2087. // they are in the order in which they appear in data array
  2088. var ordered = [];
  2089. for (var i = 0; i < ids.length; i++) {
  2090. var id = ids[i];
  2091. for (var j = 0; j < matches.length; j++) {
  2092. var match = matches[j];
  2093. if (equal(id, opts.id(match))) {
  2094. ordered.push(match);
  2095. matches.splice(j, 1);
  2096. break;
  2097. }
  2098. }
  2099. }
  2100. callback(ordered);
  2101. }
  2102. });
  2103. };
  2104. }
  2105. return opts;
  2106. },
  2107. // multi
  2108. selectChoice: function (choice) {
  2109. var selected = this.container.find(".select2-search-choice-focus");
  2110. if (selected.length && choice && choice[0] == selected[0]) {
  2111. } else {
  2112. if (selected.length) {
  2113. this.opts.element.trigger("choice-deselected", selected);
  2114. }
  2115. selected.removeClass("select2-search-choice-focus");
  2116. if (choice && choice.length) {
  2117. this.close();
  2118. choice.addClass("select2-search-choice-focus");
  2119. this.opts.element.trigger("choice-selected", choice);
  2120. }
  2121. }
  2122. },
  2123. // multi
  2124. destroy: function() {
  2125. $("label[for='" + this.search.attr('id') + "']")
  2126. .attr('for', this.opts.element.attr("id"));
  2127. this.parent.destroy.apply(this, arguments);
  2128. },
  2129. // multi
  2130. initContainer: function () {
  2131. var selector = ".select2-choices", selection;
  2132. this.searchContainer = this.container.find(".select2-search-field");
  2133. this.selection = selection = this.container.find(selector);
  2134. var _this = this;
  2135. this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) {
  2136. //killEvent(e);
  2137. _this.search[0].focus();
  2138. _this.selectChoice($(this));
  2139. });
  2140. // rewrite labels from original element to focusser
  2141. this.search.attr("id", "s2id_autogen"+nextUid());
  2142. this.search.prev()
  2143. .text($("label[for='" + this.opts.element.attr("id") + "']").text())
  2144. .attr('for', this.search.attr('id'));
  2145. this.search.on("input paste", this.bind(function() {
  2146. if (!this.isInterfaceEnabled()) return;
  2147. if (!this.opened()) {
  2148. this.open();
  2149. }
  2150. }));
  2151. this.search.attr("tabindex", this.elementTabIndex);
  2152. this.keydowns = 0;
  2153. this.search.on("keydown", this.bind(function (e) {
  2154. if (!this.isInterfaceEnabled()) return;
  2155. ++this.keydowns;
  2156. var selected = selection.find(".select2-search-choice-focus");
  2157. var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
  2158. var next = selected.next(".select2-search-choice:not(.select2-locked)");
  2159. var pos = getCursorInfo(this.search);
  2160. if (selected.length &&
  2161. (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
  2162. var selectedChoice = selected;
  2163. if (e.which == KEY.LEFT && prev.length) {
  2164. selectedChoice = prev;
  2165. }
  2166. else if (e.which == KEY.RIGHT) {
  2167. selectedChoice = next.length ? next : null;
  2168. }
  2169. else if (e.which === KEY.BACKSPACE) {
  2170. this.unselect(selected.first());
  2171. this.search.width(10);
  2172. selectedChoice = prev.length ? prev : next;
  2173. } else if (e.which == KEY.DELETE) {
  2174. this.unselect(selected.first());
  2175. this.search.width(10);
  2176. selectedChoice = next.length ? next : null;
  2177. } else if (e.which == KEY.ENTER) {
  2178. selectedChoice = null;
  2179. }
  2180. this.selectChoice(selectedChoice);
  2181. killEvent(e);
  2182. if (!selectedChoice || !selectedChoice.length) {
  2183. this.open();
  2184. }
  2185. return;
  2186. } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
  2187. || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {
  2188. this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
  2189. killEvent(e);
  2190. return;
  2191. } else {
  2192. this.selectChoice(null);
  2193. }
  2194. if (this.opened()) {
  2195. switch (e.which) {
  2196. case KEY.UP:
  2197. case KEY.DOWN:
  2198. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  2199. killEvent(e);
  2200. return;
  2201. case KEY.ENTER:
  2202. this.selectHighlighted();
  2203. killEvent(e);
  2204. return;
  2205. case KEY.TAB:
  2206. this.selectHighlighted({noFocus:true});
  2207. this.close();
  2208. return;
  2209. case KEY.ESC:
  2210. this.cancel(e);
  2211. killEvent(e);
  2212. return;
  2213. }
  2214. }
  2215. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  2216. || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  2217. return;
  2218. }
  2219. if (e.which === KEY.ENTER) {
  2220. if (this.opts.openOnEnter === false) {
  2221. return;
  2222. } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
  2223. return;
  2224. }
  2225. }
  2226. this.open();
  2227. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  2228. // prevent the page from scrolling
  2229. killEvent(e);
  2230. }
  2231. if (e.which === KEY.ENTER) {
  2232. // prevent form from being submitted
  2233. killEvent(e);
  2234. }
  2235. }));
  2236. this.search.on("keyup", this.bind(function (e) {
  2237. this.keydowns = 0;
  2238. this.resizeSearch();
  2239. })
  2240. );
  2241. this.search.on("blur", this.bind(function(e) {
  2242. this.container.removeClass("select2-container-active");
  2243. this.search.removeClass("select2-focused");
  2244. this.selectChoice(null);
  2245. if (!this.opened()) this.clearSearch();
  2246. e.stopImmediatePropagation();
  2247. this.opts.element.trigger($.Event("select2-blur"));
  2248. }));
  2249. this.container.on("click", selector, this.bind(function (e) {
  2250. if (!this.isInterfaceEnabled()) return;
  2251. if ($(e.target).closest(".select2-search-choice").length > 0) {
  2252. // clicked inside a select2 search choice, do not open
  2253. return;
  2254. }
  2255. this.selectChoice(null);
  2256. this.clearPlaceholder();
  2257. if (!this.container.hasClass("select2-container-active")) {
  2258. this.opts.element.trigger($.Event("select2-focus"));
  2259. }
  2260. this.open();
  2261. this.focusSearch();
  2262. e.preventDefault();
  2263. }));
  2264. this.container.on("focus", selector, this.bind(function () {
  2265. if (!this.isInterfaceEnabled()) return;
  2266. if (!this.container.hasClass("select2-container-active")) {
  2267. this.opts.element.trigger($.Event("select2-focus"));
  2268. }
  2269. this.container.addClass("select2-container-active");
  2270. this.dropdown.addClass("select2-drop-active");
  2271. this.clearPlaceholder();
  2272. }));
  2273. this.initContainerWidth();
  2274. this.opts.element.addClass("select2-offscreen");
  2275. // set the placeholder if necessary
  2276. this.clearSearch();
  2277. },
  2278. // multi
  2279. enableInterface: function() {
  2280. if (this.parent.enableInterface.apply(this, arguments)) {
  2281. this.search.prop("disabled", !this.isInterfaceEnabled());
  2282. }
  2283. },
  2284. // multi
  2285. initSelection: function () {
  2286. var data;
  2287. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  2288. this.updateSelection([]);
  2289. this.close();
  2290. // set the placeholder if necessary
  2291. this.clearSearch();
  2292. }
  2293. if (this.select || this.opts.element.val() !== "") {
  2294. var self = this;
  2295. this.opts.initSelection.call(null, this.opts.element, function(data){
  2296. if (data !== undefined && data !== null) {
  2297. self.updateSelection(data);
  2298. self.close();
  2299. // set the placeholder if necessary
  2300. self.clearSearch();
  2301. }
  2302. });
  2303. }
  2304. },
  2305. // multi
  2306. clearSearch: function () {
  2307. var placeholder = this.getPlaceholder(),
  2308. maxWidth = this.getMaxSearchWidth();
  2309. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  2310. this.search.val(placeholder).addClass("select2-default");
  2311. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  2312. // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944
  2313. this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
  2314. } else {
  2315. this.search.val("").width(10);
  2316. }
  2317. },
  2318. // multi
  2319. clearPlaceholder: function () {
  2320. if (this.search.hasClass("select2-default")) {
  2321. this.search.val("").removeClass("select2-default");
  2322. }
  2323. },
  2324. // multi
  2325. opening: function () {
  2326. this.clearPlaceholder(); // should be done before super so placeholder is not used to search
  2327. this.resizeSearch();
  2328. this.parent.opening.apply(this, arguments);
  2329. this.focusSearch();
  2330. // initializes search's value with nextSearchTerm (if defined by user)
  2331. // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
  2332. if(this.search.val() === "") {
  2333. if(this.nextSearchTerm != undefined){
  2334. this.search.val(this.nextSearchTerm);
  2335. this.search.select();
  2336. }
  2337. }
  2338. this.updateResults(true);
  2339. this.search.focus();
  2340. this.opts.element.trigger($.Event("select2-open"));
  2341. },
  2342. // multi
  2343. close: function () {
  2344. if (!this.opened()) return;
  2345. this.parent.close.apply(this, arguments);
  2346. },
  2347. // multi
  2348. focus: function () {
  2349. this.close();
  2350. this.search.focus();
  2351. },
  2352. // multi
  2353. isFocused: function () {
  2354. return this.search.hasClass("select2-focused");
  2355. },
  2356. // multi
  2357. updateSelection: function (data) {
  2358. var ids = [], filtered = [], self = this;
  2359. // filter out duplicates
  2360. $(data).each(function () {
  2361. if (indexOf(self.id(this), ids) < 0) {
  2362. ids.push(self.id(this));
  2363. filtered.push(this);
  2364. }
  2365. });
  2366. data = filtered;
  2367. this.selection.find(".select2-search-choice").remove();
  2368. $(data).each(function () {
  2369. self.addSelectedChoice(this);
  2370. });
  2371. self.postprocessResults();
  2372. },
  2373. // multi
  2374. tokenize: function() {
  2375. var input = this.search.val();
  2376. input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
  2377. if (input != null && input != undefined) {
  2378. this.search.val(input);
  2379. if (input.length > 0) {
  2380. this.open();
  2381. }
  2382. }
  2383. },
  2384. // multi
  2385. onSelect: function (data, options) {
  2386. if (!this.triggerSelect(data)) { return; }
  2387. this.addSelectedChoice(data);
  2388. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  2389. // keep track of the search's value before it gets cleared
  2390. this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
  2391. this.clearSearch();
  2392. this.updateResults();
  2393. if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true);
  2394. if (this.opts.closeOnSelect) {
  2395. this.close();
  2396. this.search.width(10);
  2397. } else {
  2398. if (this.countSelectableResults()>0) {
  2399. this.search.width(10);
  2400. this.resizeSearch();
  2401. if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
  2402. // if we reached max selection size repaint the results so choices
  2403. // are replaced with the max selection reached message
  2404. this.updateResults(true);
  2405. } else {
  2406. // initializes search's value with nextSearchTerm and update search result
  2407. if(this.nextSearchTerm != undefined){
  2408. this.search.val(this.nextSearchTerm);
  2409. this.updateResults();
  2410. this.search.select();
  2411. }
  2412. }
  2413. this.positionDropdown();
  2414. } else {
  2415. // if nothing left to select close
  2416. this.close();
  2417. this.search.width(10);
  2418. }
  2419. }
  2420. // since its not possible to select an element that has already been
  2421. // added we do not need to check if this is a new element before firing change
  2422. this.triggerChange({ added: data });
  2423. if (!options || !options.noFocus)
  2424. this.focusSearch();
  2425. },
  2426. // multi
  2427. cancel: function () {
  2428. this.close();
  2429. this.focusSearch();
  2430. },
  2431. addSelectedChoice: function (data) {
  2432. var enableChoice = !data.locked,
  2433. enabledItem = $(
  2434. "<li class='select2-search-choice'>" +
  2435. " <div></div>" +
  2436. " <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
  2437. "</li>"),
  2438. disabledItem = $(
  2439. "<li class='select2-search-choice select2-locked'>" +
  2440. "<div></div>" +
  2441. "</li>");
  2442. var choice = enableChoice ? enabledItem : disabledItem,
  2443. id = this.id(data),
  2444. val = this.getVal(),
  2445. formatted,
  2446. cssClass;
  2447. formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
  2448. if (formatted != undefined) {
  2449. choice.find("div").replaceWith("<div>"+formatted+"</div>");
  2450. }
  2451. cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
  2452. if (cssClass != undefined) {
  2453. choice.addClass(cssClass);
  2454. }
  2455. if(enableChoice){
  2456. choice.find(".select2-search-choice-close")
  2457. .on("mousedown", killEvent)
  2458. .on("click dblclick", this.bind(function (e) {
  2459. if (!this.isInterfaceEnabled()) return;
  2460. $(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
  2461. this.unselect($(e.target));
  2462. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  2463. this.close();
  2464. this.focusSearch();
  2465. })).dequeue();
  2466. killEvent(e);
  2467. })).on("focus", this.bind(function () {
  2468. if (!this.isInterfaceEnabled()) return;
  2469. this.container.addClass("select2-container-active");
  2470. this.dropdown.addClass("select2-drop-active");
  2471. }));
  2472. }
  2473. choice.data("select2-data", data);
  2474. choice.insertBefore(this.searchContainer);
  2475. val.push(id);
  2476. this.setVal(val);
  2477. },
  2478. // multi
  2479. unselect: function (selected) {
  2480. var val = this.getVal(),
  2481. data,
  2482. index;
  2483. selected = selected.closest(".select2-search-choice");
  2484. if (selected.length === 0) {
  2485. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  2486. }
  2487. data = selected.data("select2-data");
  2488. if (!data) {
  2489. // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
  2490. // and invoked on an element already removed
  2491. return;
  2492. }
  2493. while((index = indexOf(this.id(data), val)) >= 0) {
  2494. val.splice(index, 1);
  2495. this.setVal(val);
  2496. if (this.select) this.postprocessResults();
  2497. }
  2498. var evt = $.Event("select2-removing");
  2499. evt.val = this.id(data);
  2500. evt.choice = data;
  2501. this.opts.element.trigger(evt);
  2502. if (evt.isDefaultPrevented()) {
  2503. return;
  2504. }
  2505. selected.remove();
  2506. this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
  2507. this.triggerChange({ removed: data });
  2508. },
  2509. // multi
  2510. postprocessResults: function (data, initial, noHighlightUpdate) {
  2511. var val = this.getVal(),
  2512. choices = this.results.find(".select2-result"),
  2513. compound = this.results.find(".select2-result-with-children"),
  2514. self = this;
  2515. choices.each2(function (i, choice) {
  2516. var id = self.id(choice.data("select2-data"));
  2517. if (indexOf(id, val) >= 0) {
  2518. choice.addClass("select2-selected");
  2519. // mark all children of the selected parent as selected
  2520. choice.find(".select2-result-selectable").addClass("select2-selected");
  2521. }
  2522. });
  2523. compound.each2(function(i, choice) {
  2524. // hide an optgroup if it doesn't have any selectable children
  2525. if (!choice.is('.select2-result-selectable')
  2526. && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
  2527. choice.addClass("select2-selected");
  2528. }
  2529. });
  2530. if (this.highlight() == -1 && noHighlightUpdate !== false){
  2531. self.highlight(0);
  2532. }
  2533. //If all results are chosen render formatNoMatches
  2534. if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
  2535. if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
  2536. if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
  2537. this.results.append("<li class='select2-no-results'>" + self.opts.formatNoMatches(self.search.val()) + "</li>");
  2538. }
  2539. }
  2540. }
  2541. },
  2542. // multi
  2543. getMaxSearchWidth: function() {
  2544. return this.selection.width() - getSideBorderPadding(this.search);
  2545. },
  2546. // multi
  2547. resizeSearch: function () {
  2548. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  2549. sideBorderPadding = getSideBorderPadding(this.search);
  2550. minimumWidth = measureTextWidth(this.search) + 10;
  2551. left = this.search.offset().left;
  2552. maxWidth = this.selection.width();
  2553. containerLeft = this.selection.offset().left;
  2554. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  2555. if (searchWidth < minimumWidth) {
  2556. searchWidth = maxWidth - sideBorderPadding;
  2557. }
  2558. if (searchWidth < 40) {
  2559. searchWidth = maxWidth - sideBorderPadding;
  2560. }
  2561. if (searchWidth <= 0) {
  2562. searchWidth = minimumWidth;
  2563. }
  2564. this.search.width(Math.floor(searchWidth));
  2565. },
  2566. // multi
  2567. getVal: function () {
  2568. var val;
  2569. if (this.select) {
  2570. val = this.select.val();
  2571. return val === null ? [] : val;
  2572. } else {
  2573. val = this.opts.element.val();
  2574. return splitVal(val, this.opts.separator);
  2575. }
  2576. },
  2577. // multi
  2578. setVal: function (val) {
  2579. var unique;
  2580. if (this.select) {
  2581. this.select.val(val);
  2582. } else {
  2583. unique = [];
  2584. // filter out duplicates
  2585. $(val).each(function () {
  2586. if (indexOf(this, unique) < 0) unique.push(this);
  2587. });
  2588. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  2589. }
  2590. },
  2591. // multi
  2592. buildChangeDetails: function (old, current) {
  2593. var current = current.slice(0),
  2594. old = old.slice(0);
  2595. // remove intersection from each array
  2596. for (var i = 0; i < current.length; i++) {
  2597. for (var j = 0; j < old.length; j++) {
  2598. if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
  2599. current.splice(i, 1);
  2600. if(i>0){
  2601. i--;
  2602. }
  2603. old.splice(j, 1);
  2604. j--;
  2605. }
  2606. }
  2607. }
  2608. return {added: current, removed: old};
  2609. },
  2610. // multi
  2611. val: function (val, triggerChange) {
  2612. var oldData, self=this;
  2613. if (arguments.length === 0) {
  2614. return this.getVal();
  2615. }
  2616. oldData=this.data();
  2617. if (!oldData.length) oldData=[];
  2618. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2619. if (!val && val !== 0) {
  2620. this.opts.element.val("");
  2621. this.updateSelection([]);
  2622. this.clearSearch();
  2623. if (triggerChange) {
  2624. this.triggerChange({added: this.data(), removed: oldData});
  2625. }
  2626. return;
  2627. }
  2628. // val is a list of ids
  2629. this.setVal(val);
  2630. if (this.select) {
  2631. this.opts.initSelection(this.select, this.bind(this.updateSelection));
  2632. if (triggerChange) {
  2633. this.triggerChange(this.buildChangeDetails(oldData, this.data()));
  2634. }
  2635. } else {
  2636. if (this.opts.initSelection === undefined) {
  2637. throw new Error("val() cannot be called if initSelection() is not defined");
  2638. }
  2639. this.opts.initSelection(this.opts.element, function(data){
  2640. var ids=$.map(data, self.id);
  2641. self.setVal(ids);
  2642. self.updateSelection(data);
  2643. self.clearSearch();
  2644. if (triggerChange) {
  2645. self.triggerChange(self.buildChangeDetails(oldData, self.data()));
  2646. }
  2647. });
  2648. }
  2649. this.clearSearch();
  2650. },
  2651. // multi
  2652. onSortStart: function() {
  2653. if (this.select) {
  2654. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  2655. }
  2656. // collapse search field into 0 width so its container can be collapsed as well
  2657. this.search.width(0);
  2658. // hide the container
  2659. this.searchContainer.hide();
  2660. },
  2661. // multi
  2662. onSortEnd:function() {
  2663. var val=[], self=this;
  2664. // show search and move it to the end of the list
  2665. this.searchContainer.show();
  2666. // make sure the search container is the last item in the list
  2667. this.searchContainer.appendTo(this.searchContainer.parent());
  2668. // since we collapsed the width in dragStarted, we resize it here
  2669. this.resizeSearch();
  2670. // update selection
  2671. this.selection.find(".select2-search-choice").each(function() {
  2672. val.push(self.opts.id($(this).data("select2-data")));
  2673. });
  2674. this.setVal(val);
  2675. this.triggerChange();
  2676. },
  2677. // multi
  2678. data: function(values, triggerChange) {
  2679. var self=this, ids, old;
  2680. if (arguments.length === 0) {
  2681. return this.selection
  2682. .children(".select2-search-choice")
  2683. .map(function() { return $(this).data("select2-data"); })
  2684. .get();
  2685. } else {
  2686. old = this.data();
  2687. if (!values) { values = []; }
  2688. ids = $.map(values, function(e) { return self.opts.id(e); });
  2689. this.setVal(ids);
  2690. this.updateSelection(values);
  2691. this.clearSearch();
  2692. if (triggerChange) {
  2693. this.triggerChange(this.buildChangeDetails(old, this.data()));
  2694. }
  2695. }
  2696. }
  2697. });
  2698. $.fn.select2 = function () {
  2699. var args = Array.prototype.slice.call(arguments, 0),
  2700. opts,
  2701. select2,
  2702. method, value, multiple,
  2703. allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"],
  2704. valueMethods = ["opened", "isFocused", "container", "dropdown"],
  2705. propertyMethods = ["val", "data"],
  2706. methodsMap = { search: "externalSearch" };
  2707. this.each(function () {
  2708. if (args.length === 0 || typeof(args[0]) === "object") {
  2709. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  2710. opts.element = $(this);
  2711. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2712. multiple = opts.element.prop("multiple");
  2713. } else {
  2714. multiple = opts.multiple || false;
  2715. if ("tags" in opts) {opts.multiple = multiple = true;}
  2716. }
  2717. select2 = multiple ? new window.Select2["class"].multi() : new window.Select2["class"].single();
  2718. select2.init(opts);
  2719. } else if (typeof(args[0]) === "string") {
  2720. if (indexOf(args[0], allowedMethods) < 0) {
  2721. throw "Unknown method: " + args[0];
  2722. }
  2723. value = undefined;
  2724. select2 = $(this).data("select2");
  2725. if (select2 === undefined) return;
  2726. method=args[0];
  2727. if (method === "container") {
  2728. value = select2.container;
  2729. } else if (method === "dropdown") {
  2730. value = select2.dropdown;
  2731. } else {
  2732. if (methodsMap[method]) method = methodsMap[method];
  2733. value = select2[method].apply(select2, args.slice(1));
  2734. }
  2735. if (indexOf(args[0], valueMethods) >= 0
  2736. || (indexOf(args[0], propertyMethods) && args.length == 1)) {
  2737. return false; // abort the iteration, ready to return first matched value
  2738. }
  2739. } else {
  2740. throw "Invalid arguments to select2 plugin: " + args;
  2741. }
  2742. });
  2743. return (value === undefined) ? this : value;
  2744. };
  2745. // plugin defaults, accessible to users
  2746. $.fn.select2.defaults = {
  2747. width: "copy",
  2748. loadMorePadding: 0,
  2749. closeOnSelect: true,
  2750. openOnEnter: true,
  2751. containerCss: {},
  2752. dropdownCss: {},
  2753. containerCssClass: "",
  2754. dropdownCssClass: "",
  2755. formatResult: function(result, container, query, escapeMarkup) {
  2756. var markup=[];
  2757. markMatch(result.text, query.term, markup, escapeMarkup);
  2758. return markup.join("");
  2759. },
  2760. formatSelection: function (data, container, escapeMarkup) {
  2761. return data ? escapeMarkup(data.text) : undefined;
  2762. },
  2763. sortResults: function (results, container, query) {
  2764. return results;
  2765. },
  2766. formatResultCssClass: function(data) {return data.css;},
  2767. formatSelectionCssClass: function(data, container) {return undefined;},
  2768. formatMatches: function (matches) { return matches + " results are available, use up and down arrow keys to navigate."; },
  2769. formatNoMatches: function () { return "No matches found"; },
  2770. formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1? "" : "s"); },
  2771. formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
  2772. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
  2773. formatLoadMore: function (pageNumber) { return "Loading more results…"; },
  2774. formatSearching: function () { return "Searching…"; },
  2775. minimumResultsForSearch: 0,
  2776. minimumInputLength: 0,
  2777. maximumInputLength: null,
  2778. maximumSelectionSize: 0,
  2779. id: function (e) { return e == undefined ? null : e.id; },
  2780. matcher: function(term, text) {
  2781. return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
  2782. },
  2783. separator: ",",
  2784. tokenSeparators: [],
  2785. tokenizer: defaultTokenizer,
  2786. escapeMarkup: defaultEscapeMarkup,
  2787. blurOnChange: false,
  2788. selectOnBlur: false,
  2789. adaptContainerCssClass: function(c) { return c; },
  2790. adaptDropdownCssClass: function(c) { return null; },
  2791. nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; },
  2792. searchInputPlaceholder: ''
  2793. };
  2794. $.fn.select2.ajaxDefaults = {
  2795. transport: $.ajax,
  2796. params: {
  2797. type: "GET",
  2798. cache: false,
  2799. dataType: "json"
  2800. }
  2801. };
  2802. // exports
  2803. window.Select2 = {
  2804. query: {
  2805. ajax: ajax,
  2806. local: local,
  2807. tags: tags
  2808. }, util: {
  2809. debounce: debounce,
  2810. markMatch: markMatch,
  2811. escapeMarkup: defaultEscapeMarkup,
  2812. stripDiacritics: stripDiacritics
  2813. }, "class": {
  2814. "abstract": AbstractSelect2,
  2815. "single": SingleSelect2,
  2816. "multi": MultiSelect2
  2817. }
  2818. };
  2819. }(jQuery));