select2.js 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541
  1. /*
  2. Copyright 2012 Igor Vaynberg
  3. Version: 3.5.2 Timestamp: Sat Nov 1 14:43:36 EDT 2014
  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 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","\u0386":"\u0391","\u0388":"\u0395","\u0389":"\u0397","\u038A":"\u0399","\u03AA":"\u0399","\u038C":"\u039F","\u038E":"\u03A5","\u03AB":"\u03A5","\u038F":"\u03A9","\u03AC":"\u03B1","\u03AD":"\u03B5","\u03AE":"\u03B7","\u03AF":"\u03B9","\u03CA":"\u03B9","\u0390":"\u03B9","\u03CC":"\u03BF","\u03CD":"\u03C5","\u03CB":"\u03C5","\u03B0":"\u03C5","\u03C9":"\u03C9","\u03C2":"\u03C3"};
  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. // Used 'uni range + named function' from http://jsperf.com/diacritics/18
  100. function match(a) {
  101. return DIACRITICS[a] || a;
  102. }
  103. return str.replace(/[^\u0000-\u007E]/g, match);
  104. }
  105. function indexOf(value, array) {
  106. var i = 0, l = array.length;
  107. for (; i < l; i = i + 1) {
  108. if (equal(value, array[i])) return i;
  109. }
  110. return -1;
  111. }
  112. function measureScrollbar () {
  113. var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
  114. $template.appendTo(document.body);
  115. var dim = {
  116. width: $template.width() - $template[0].clientWidth,
  117. height: $template.height() - $template[0].clientHeight
  118. };
  119. $template.remove();
  120. return dim;
  121. }
  122. /**
  123. * Compares equality of a and b
  124. * @param a
  125. * @param b
  126. */
  127. function equal(a, b) {
  128. if (a === b) return true;
  129. if (a === undefined || b === undefined) return false;
  130. if (a === null || b === null) return false;
  131. // Check whether 'a' or 'b' is a string (primitive or object).
  132. // The concatenation of an empty string (+'') converts its argument to a string's primitive.
  133. if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object
  134. if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object
  135. return false;
  136. }
  137. /**
  138. * Splits the string into an array of values, transforming each value. An empty array is returned for nulls or empty
  139. * strings
  140. * @param string
  141. * @param separator
  142. */
  143. function splitVal(string, separator, transform) {
  144. var val, i, l;
  145. if (string === null || string.length < 1) return [];
  146. val = string.split(separator);
  147. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = transform(val[i]);
  148. return val;
  149. }
  150. function getSideBorderPadding(element) {
  151. return element.outerWidth(false) - element.width();
  152. }
  153. function installKeyUpChangeEvent(element) {
  154. var key="keyup-change-value";
  155. element.on("keydown", function () {
  156. if ($.data(element, key) === undefined) {
  157. $.data(element, key, element.val());
  158. }
  159. });
  160. element.on("keyup", function () {
  161. var val= $.data(element, key);
  162. if (val !== undefined && element.val() !== val) {
  163. $.removeData(element, key);
  164. element.trigger("keyup-change");
  165. }
  166. });
  167. }
  168. /**
  169. * filters mouse events so an event is fired only if the mouse moved.
  170. *
  171. * filters out mouse events that occur when mouse is stationary but
  172. * the elements under the pointer are scrolled.
  173. */
  174. function installFilteredMouseMove(element) {
  175. element.on("mousemove", function (e) {
  176. var lastpos = lastMousePosition;
  177. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  178. $(e.target).trigger("mousemove-filtered", e);
  179. }
  180. });
  181. }
  182. /**
  183. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  184. * within the last quietMillis milliseconds.
  185. *
  186. * @param quietMillis number of milliseconds to wait before invoking fn
  187. * @param fn function to be debounced
  188. * @param ctx object to be used as this reference within fn
  189. * @return debounced version of fn
  190. */
  191. function debounce(quietMillis, fn, ctx) {
  192. ctx = ctx || undefined;
  193. var timeout;
  194. return function () {
  195. var args = arguments;
  196. window.clearTimeout(timeout);
  197. timeout = window.setTimeout(function() {
  198. fn.apply(ctx, args);
  199. }, quietMillis);
  200. };
  201. }
  202. function installDebouncedScroll(threshold, element) {
  203. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  204. element.on("scroll", function (e) {
  205. if (indexOf(e.target, element.get()) >= 0) notify(e);
  206. });
  207. }
  208. function focus($el) {
  209. if ($el[0] === document.activeElement) return;
  210. /* set the focus in a 0 timeout - that way the focus is set after the processing
  211. of the current event has finished - which seems like the only reliable way
  212. to set focus */
  213. window.setTimeout(function() {
  214. var el=$el[0], pos=$el.val().length, range;
  215. $el.focus();
  216. /* make sure el received focus so we do not error out when trying to manipulate the caret.
  217. sometimes modals or others listeners may steal it after its set */
  218. var isVisible = (el.offsetWidth > 0 || el.offsetHeight > 0);
  219. if (isVisible && el === document.activeElement) {
  220. /* after the focus is set move the caret to the end, necessary when we val()
  221. just before setting focus */
  222. if(el.setSelectionRange)
  223. {
  224. el.setSelectionRange(pos, pos);
  225. }
  226. else if (el.createTextRange) {
  227. range = el.createTextRange();
  228. range.collapse(false);
  229. range.select();
  230. }
  231. }
  232. }, 0);
  233. }
  234. function getCursorInfo(el) {
  235. el = $(el)[0];
  236. var offset = 0;
  237. var length = 0;
  238. if ('selectionStart' in el) {
  239. offset = el.selectionStart;
  240. length = el.selectionEnd - offset;
  241. } else if ('selection' in document) {
  242. el.focus();
  243. var sel = document.selection.createRange();
  244. length = document.selection.createRange().text.length;
  245. sel.moveStart('character', -el.value.length);
  246. offset = sel.text.length - length;
  247. }
  248. return { offset: offset, length: length };
  249. }
  250. function killEvent(event) {
  251. event.preventDefault();
  252. event.stopPropagation();
  253. }
  254. function killEventImmediately(event) {
  255. event.preventDefault();
  256. event.stopImmediatePropagation();
  257. }
  258. function measureTextWidth(e) {
  259. if (!sizer){
  260. var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
  261. sizer = $(document.createElement("div")).css({
  262. position: "absolute",
  263. left: "-10000px",
  264. top: "-10000px",
  265. display: "none",
  266. fontSize: style.fontSize,
  267. fontFamily: style.fontFamily,
  268. fontStyle: style.fontStyle,
  269. fontWeight: style.fontWeight,
  270. letterSpacing: style.letterSpacing,
  271. textTransform: style.textTransform,
  272. whiteSpace: "nowrap"
  273. });
  274. sizer.attr("class","select2-sizer");
  275. $(document.body).append(sizer);
  276. }
  277. sizer.text(e.val());
  278. return sizer.width();
  279. }
  280. function syncCssClasses(dest, src, adapter) {
  281. var classes, replacements = [], adapted;
  282. classes = $.trim(dest.attr("class"));
  283. if (classes) {
  284. classes = '' + classes; // for IE which returns object
  285. $(classes.split(/\s+/)).each2(function() {
  286. if (this.indexOf("select2-") === 0) {
  287. replacements.push(this);
  288. }
  289. });
  290. }
  291. classes = $.trim(src.attr("class"));
  292. if (classes) {
  293. classes = '' + classes; // for IE which returns object
  294. $(classes.split(/\s+/)).each2(function() {
  295. if (this.indexOf("select2-") !== 0) {
  296. adapted = adapter(this);
  297. if (adapted) {
  298. replacements.push(adapted);
  299. }
  300. }
  301. });
  302. }
  303. dest.attr("class", replacements.join(" "));
  304. }
  305. function markMatch(text, term, markup, escapeMarkup) {
  306. var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())),
  307. tl=term.length;
  308. if (match<0) {
  309. markup.push(escapeMarkup(text));
  310. return;
  311. }
  312. markup.push(escapeMarkup(text.substring(0, match)));
  313. markup.push("<span class='select2-match'>");
  314. markup.push(escapeMarkup(text.substring(match, match + tl)));
  315. markup.push("</span>");
  316. markup.push(escapeMarkup(text.substring(match + tl, text.length)));
  317. }
  318. function defaultEscapeMarkup(markup) {
  319. var replace_map = {
  320. '\\': '&#92;',
  321. '&': '&amp;',
  322. '<': '&lt;',
  323. '>': '&gt;',
  324. '"': '&quot;',
  325. "'": '&#39;',
  326. "/": '&#47;'
  327. };
  328. return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
  329. return replace_map[match];
  330. });
  331. }
  332. /**
  333. * Produces an ajax-based query function
  334. *
  335. * @param options object containing configuration parameters
  336. * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax
  337. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  338. * @param options.url url for the data
  339. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  340. * @param options.dataType request data type: ajax, jsonp, other datatypes supported by jQuery's $.ajax function or the transport function if specified
  341. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  342. * @param options.results a function(remoteData, pageNumber, query) that converts data returned form the remote request to the format expected by Select2.
  343. * The expected format is an object containing the following keys:
  344. * results array of objects that will be used as choices
  345. * more (optional) boolean indicating whether there are more results available
  346. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  347. */
  348. function ajax(options) {
  349. var timeout, // current scheduled but not yet executed request
  350. handler = null,
  351. quietMillis = options.quietMillis || 100,
  352. ajaxUrl = options.url,
  353. self = this;
  354. return function (query) {
  355. window.clearTimeout(timeout);
  356. timeout = window.setTimeout(function () {
  357. var data = options.data, // ajax data function
  358. url = ajaxUrl, // ajax url string or function
  359. transport = options.transport || $.fn.select2.ajaxDefaults.transport,
  360. // deprecated - to be removed in 4.0 - use params instead
  361. deprecated = {
  362. type: options.type || 'GET', // set type of request (GET or POST)
  363. cache: options.cache || false,
  364. jsonpCallback: options.jsonpCallback||undefined,
  365. dataType: options.dataType||"json"
  366. },
  367. params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
  368. data = data ? data.call(self, query.term, query.page, query.context) : null;
  369. url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
  370. if (handler && typeof handler.abort === "function") { handler.abort(); }
  371. if (options.params) {
  372. if ($.isFunction(options.params)) {
  373. $.extend(params, options.params.call(self));
  374. } else {
  375. $.extend(params, options.params);
  376. }
  377. }
  378. $.extend(params, {
  379. url: url,
  380. dataType: options.dataType,
  381. data: data,
  382. success: function (data) {
  383. // TODO - replace query.page with query so users have access to term, page, etc.
  384. // added query as third paramter to keep backwards compatibility
  385. var results = options.results(data, query.page, query);
  386. query.callback(results);
  387. },
  388. error: function(jqXHR, textStatus, errorThrown){
  389. var results = {
  390. hasError: true,
  391. jqXHR: jqXHR,
  392. textStatus: textStatus,
  393. errorThrown: errorThrown
  394. };
  395. query.callback(results);
  396. }
  397. });
  398. handler = transport.call(self, params);
  399. }, quietMillis);
  400. };
  401. }
  402. /**
  403. * Produces a query function that works with a local array
  404. *
  405. * @param options object containing configuration parameters. The options parameter can either be an array or an
  406. * object.
  407. *
  408. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  409. *
  410. * If the object form is used it is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  411. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  412. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  413. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  414. * the text.
  415. */
  416. function local(options) {
  417. var data = options, // data elements
  418. dataText,
  419. tmp,
  420. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  421. if ($.isArray(data)) {
  422. tmp = data;
  423. data = { results: tmp };
  424. }
  425. if ($.isFunction(data) === false) {
  426. tmp = data;
  427. data = function() { return tmp; };
  428. }
  429. var dataItem = data();
  430. if (dataItem.text) {
  431. text = dataItem.text;
  432. // if text is not a function we assume it to be a key name
  433. if (!$.isFunction(text)) {
  434. 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
  435. text = function (item) { return item[dataText]; };
  436. }
  437. }
  438. return function (query) {
  439. var t = query.term, filtered = { results: [] }, process;
  440. if (t === "") {
  441. query.callback(data());
  442. return;
  443. }
  444. process = function(datum, collection) {
  445. var group, attr;
  446. datum = datum[0];
  447. if (datum.children) {
  448. group = {};
  449. for (attr in datum) {
  450. if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
  451. }
  452. group.children=[];
  453. $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
  454. if (group.children.length || query.matcher(t, text(group), datum)) {
  455. collection.push(group);
  456. }
  457. } else {
  458. if (query.matcher(t, text(datum), datum)) {
  459. collection.push(datum);
  460. }
  461. }
  462. };
  463. $(data().results).each2(function(i, datum) { process(datum, filtered.results); });
  464. query.callback(filtered);
  465. };
  466. }
  467. // TODO javadoc
  468. function tags(data) {
  469. var isFunc = $.isFunction(data);
  470. return function (query) {
  471. var t = query.term, filtered = {results: []};
  472. var result = isFunc ? data(query) : data;
  473. if ($.isArray(result)) {
  474. $(result).each(function () {
  475. var isObject = this.text !== undefined,
  476. text = isObject ? this.text : this;
  477. if (t === "" || query.matcher(t, text)) {
  478. filtered.results.push(isObject ? this : {id: this, text: this});
  479. }
  480. });
  481. query.callback(filtered);
  482. }
  483. };
  484. }
  485. /**
  486. * Checks if the formatter function should be used.
  487. *
  488. * Throws an error if it is not a function. Returns true if it should be used,
  489. * false if no formatting should be performed.
  490. *
  491. * @param formatter
  492. */
  493. function checkFormatter(formatter, formatterName) {
  494. if ($.isFunction(formatter)) return true;
  495. if (!formatter) return false;
  496. if (typeof(formatter) === 'string') return true;
  497. throw new Error(formatterName +" must be a string, function, or falsy value");
  498. }
  499. /**
  500. * Returns a given value
  501. * If given a function, returns its output
  502. *
  503. * @param val string|function
  504. * @param context value of "this" to be passed to function
  505. * @returns {*}
  506. */
  507. function evaluate(val, context) {
  508. if ($.isFunction(val)) {
  509. var args = Array.prototype.slice.call(arguments, 2);
  510. return val.apply(context, args);
  511. }
  512. return val;
  513. }
  514. function countResults(results) {
  515. var count = 0;
  516. $.each(results, function(i, item) {
  517. if (item.children) {
  518. count += countResults(item.children);
  519. } else {
  520. count++;
  521. }
  522. });
  523. return count;
  524. }
  525. /**
  526. * Default tokenizer. This function uses breaks the input on substring match of any string from the
  527. * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
  528. * two options have to be defined in order for the tokenizer to work.
  529. *
  530. * @param input text user has typed so far or pasted into the search field
  531. * @param selection currently selected choices
  532. * @param selectCallback function(choice) callback tho add the choice to selection
  533. * @param opts select2's opts
  534. * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
  535. */
  536. function defaultTokenizer(input, selection, selectCallback, opts) {
  537. var original = input, // store the original so we can compare and know if we need to tell the search to update its text
  538. dupe = false, // check for whether a token we extracted represents a duplicate selected choice
  539. token, // token
  540. index, // position at which the separator was found
  541. i, l, // looping variables
  542. separator; // the matched separator
  543. if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
  544. while (true) {
  545. index = -1;
  546. for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
  547. separator = opts.tokenSeparators[i];
  548. index = input.indexOf(separator);
  549. if (index >= 0) break;
  550. }
  551. if (index < 0) break; // did not find any token separator in the input string, bail
  552. token = input.substring(0, index);
  553. input = input.substring(index + separator.length);
  554. if (token.length > 0) {
  555. token = opts.createSearchChoice.call(this, token, selection);
  556. if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
  557. dupe = false;
  558. for (i = 0, l = selection.length; i < l; i++) {
  559. if (equal(opts.id(token), opts.id(selection[i]))) {
  560. dupe = true; break;
  561. }
  562. }
  563. if (!dupe) selectCallback(token);
  564. }
  565. }
  566. }
  567. if (original!==input) return input;
  568. }
  569. function cleanupJQueryElements() {
  570. var self = this;
  571. $.each(arguments, function (i, element) {
  572. self[element].remove();
  573. self[element] = null;
  574. });
  575. }
  576. /**
  577. * Creates a new class
  578. *
  579. * @param superClass
  580. * @param methods
  581. */
  582. function clazz(SuperClass, methods) {
  583. var constructor = function () {};
  584. constructor.prototype = new SuperClass;
  585. constructor.prototype.constructor = constructor;
  586. constructor.prototype.parent = SuperClass.prototype;
  587. constructor.prototype = $.extend(constructor.prototype, methods);
  588. return constructor;
  589. }
  590. AbstractSelect2 = clazz(Object, {
  591. // abstract
  592. bind: function (func) {
  593. var self = this;
  594. return function () {
  595. func.apply(self, arguments);
  596. };
  597. },
  598. // abstract
  599. init: function (opts) {
  600. var results, search, resultsSelector = ".select2-results";
  601. // prepare options
  602. this.opts = opts = this.prepareOpts(opts);
  603. this.id=opts.id;
  604. // destroy if called on an existing component
  605. if (opts.element.data("select2") !== undefined &&
  606. opts.element.data("select2") !== null) {
  607. opts.element.data("select2").destroy();
  608. }
  609. this.container = this.createContainer();
  610. this.liveRegion = $('.select2-hidden-accessible');
  611. if (this.liveRegion.length == 0) {
  612. this.liveRegion = $("<span>", {
  613. role: "status",
  614. "aria-live": "polite"
  615. })
  616. .addClass("select2-hidden-accessible")
  617. .appendTo(document.body);
  618. }
  619. this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
  620. this.containerEventName= this.containerId
  621. .replace(/([.])/g, '_')
  622. .replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
  623. this.container.attr("id", this.containerId);
  624. this.container.attr("title", opts.element.attr("title"));
  625. this.body = $(document.body);
  626. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  627. this.container.attr("style", opts.element.attr("style"));
  628. this.container.css(evaluate(opts.containerCss, this.opts.element));
  629. this.container.addClass(evaluate(opts.containerCssClass, this.opts.element));
  630. this.elementTabIndex = this.opts.element.attr("tabindex");
  631. // swap container for the element
  632. this.opts.element
  633. .data("select2", this)
  634. .attr("tabindex", "-1")
  635. .before(this.container)
  636. .on("click.select2", killEvent); // do not leak click events
  637. this.container.data("select2", this);
  638. this.dropdown = this.container.find(".select2-drop");
  639. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  640. this.dropdown.addClass(evaluate(opts.dropdownCssClass, this.opts.element));
  641. this.dropdown.data("select2", this);
  642. this.dropdown.on("click", killEvent);
  643. this.results = results = this.container.find(resultsSelector);
  644. this.search = search = this.container.find("input.select2-input");
  645. this.queryCount = 0;
  646. this.resultsPage = 0;
  647. this.context = null;
  648. // initialize the container
  649. this.initContainer();
  650. this.container.on("click", killEvent);
  651. installFilteredMouseMove(this.results);
  652. this.dropdown.on("mousemove-filtered", resultsSelector, this.bind(this.highlightUnderEvent));
  653. this.dropdown.on("touchstart touchmove touchend", resultsSelector, this.bind(function (event) {
  654. this._touchEvent = true;
  655. this.highlightUnderEvent(event);
  656. }));
  657. this.dropdown.on("touchmove", resultsSelector, this.bind(this.touchMoved));
  658. this.dropdown.on("touchstart touchend", resultsSelector, this.bind(this.clearTouchMoved));
  659. // Waiting for a click event on touch devices to select option and hide dropdown
  660. // otherwise click will be triggered on an underlying element
  661. this.dropdown.on('click', this.bind(function (event) {
  662. if (this._touchEvent) {
  663. this._touchEvent = false;
  664. this.selectHighlighted();
  665. }
  666. }));
  667. installDebouncedScroll(80, this.results);
  668. this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));
  669. // do not propagate change event from the search field out of the component
  670. $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
  671. $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});
  672. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  673. if ($.fn.mousewheel) {
  674. results.mousewheel(function (e, delta, deltaX, deltaY) {
  675. var top = results.scrollTop();
  676. if (deltaY > 0 && top - deltaY <= 0) {
  677. results.scrollTop(0);
  678. killEvent(e);
  679. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  680. results.scrollTop(results.get(0).scrollHeight - results.height());
  681. killEvent(e);
  682. }
  683. });
  684. }
  685. installKeyUpChangeEvent(search);
  686. search.on("keyup-change input paste", this.bind(this.updateResults));
  687. search.on("focus", function () { search.addClass("select2-focused"); });
  688. search.on("blur", function () { search.removeClass("select2-focused");});
  689. this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
  690. if ($(e.target).closest(".select2-result-selectable").length > 0) {
  691. this.highlightUnderEvent(e);
  692. this.selectHighlighted(e);
  693. }
  694. }));
  695. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  696. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  697. // dom it will trigger the popup close, which is not what we want
  698. // focusin can cause focus wars between modals and select2 since the dropdown is outside the modal.
  699. this.dropdown.on("click mouseup mousedown touchstart touchend focusin", function (e) { e.stopPropagation(); });
  700. this.nextSearchTerm = undefined;
  701. if ($.isFunction(this.opts.initSelection)) {
  702. // initialize selection based on the current value of the source element
  703. this.initSelection();
  704. // if the user has provided a function that can set selection based on the value of the source element
  705. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  706. this.monitorSource();
  707. }
  708. if (opts.maximumInputLength !== null) {
  709. this.search.attr("maxlength", opts.maximumInputLength);
  710. }
  711. var disabled = opts.element.prop("disabled");
  712. if (disabled === undefined) disabled = false;
  713. this.enable(!disabled);
  714. var readonly = opts.element.prop("readonly");
  715. if (readonly === undefined) readonly = false;
  716. this.readonly(readonly);
  717. // Calculate size of scrollbar
  718. scrollBarDimensions = scrollBarDimensions || measureScrollbar();
  719. this.autofocus = opts.element.prop("autofocus");
  720. opts.element.prop("autofocus", false);
  721. if (this.autofocus) this.focus();
  722. this.search.attr("placeholder", opts.searchInputPlaceholder);
  723. },
  724. // abstract
  725. destroy: function () {
  726. var element=this.opts.element, select2 = element.data("select2"), self = this;
  727. this.close();
  728. if (element.length && element[0].detachEvent && self._sync) {
  729. element.each(function () {
  730. if (self._sync) {
  731. this.detachEvent("onpropertychange", self._sync);
  732. }
  733. });
  734. }
  735. if (this.propertyObserver) {
  736. this.propertyObserver.disconnect();
  737. this.propertyObserver = null;
  738. }
  739. this._sync = null;
  740. if (select2 !== undefined) {
  741. select2.container.remove();
  742. select2.liveRegion.remove();
  743. select2.dropdown.remove();
  744. element
  745. .show()
  746. .removeData("select2")
  747. .off(".select2")
  748. .prop("autofocus", this.autofocus || false);
  749. if (this.elementTabIndex) {
  750. element.attr({tabindex: this.elementTabIndex});
  751. } else {
  752. element.removeAttr("tabindex");
  753. }
  754. element.show();
  755. }
  756. cleanupJQueryElements.call(this,
  757. "container",
  758. "liveRegion",
  759. "dropdown",
  760. "results",
  761. "search"
  762. );
  763. },
  764. // abstract
  765. optionToData: function(element) {
  766. if (element.is("option")) {
  767. return {
  768. id:element.prop("value"),
  769. text:element.text(),
  770. element: element.get(),
  771. css: element.attr("class"),
  772. disabled: element.prop("disabled"),
  773. locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
  774. };
  775. } else if (element.is("optgroup")) {
  776. return {
  777. text:element.attr("label"),
  778. children:[],
  779. element: element.get(),
  780. css: element.attr("class")
  781. };
  782. }
  783. },
  784. // abstract
  785. prepareOpts: function (opts) {
  786. var element, select, idKey, ajaxUrl, self = this;
  787. element = opts.element;
  788. if (element.get(0).tagName.toLowerCase() === "select") {
  789. this.select = select = opts.element;
  790. }
  791. if (select) {
  792. // these options are not allowed when attached to a select because they are picked up off the element itself
  793. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  794. if (this in opts) {
  795. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  796. }
  797. });
  798. }
  799. opts = $.extend({}, {
  800. populateResults: function(container, results, query) {
  801. var populate, id=this.opts.id, liveRegion=this.liveRegion;
  802. populate=function(results, container, depth) {
  803. var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
  804. results = opts.sortResults(results, container, query);
  805. // collect the created nodes for bulk append
  806. var nodes = [];
  807. for (i = 0, l = results.length; i < l; i = i + 1) {
  808. result=results[i];
  809. disabled = (result.disabled === true);
  810. selectable = (!disabled) && (id(result) !== undefined);
  811. compound=result.children && result.children.length > 0;
  812. node=$("<li></li>");
  813. node.addClass("select2-results-dept-"+depth);
  814. node.addClass("select2-result");
  815. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  816. if (disabled) { node.addClass("select2-disabled"); }
  817. if (compound) { node.addClass("select2-result-with-children"); }
  818. node.addClass(self.opts.formatResultCssClass(result));
  819. node.attr("role", "presentation");
  820. label=$(document.createElement("div"));
  821. label.addClass("select2-result-label");
  822. label.attr("id", "select2-result-label-" + nextUid());
  823. label.attr("role", "option");
  824. formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
  825. if (formatted!==undefined) {
  826. label.html(formatted);
  827. node.append(label);
  828. }
  829. if (compound) {
  830. innerContainer=$("<ul></ul>");
  831. innerContainer.addClass("select2-result-sub");
  832. populate(result.children, innerContainer, depth+1);
  833. node.append(innerContainer);
  834. }
  835. node.data("select2-data", result);
  836. nodes.push(node[0]);
  837. }
  838. // bulk append the created nodes
  839. container.append(nodes);
  840. liveRegion.text(opts.formatMatches(results.length));
  841. };
  842. populate(results, container, 0);
  843. }
  844. }, $.fn.select2.defaults, opts);
  845. if (typeof(opts.id) !== "function") {
  846. idKey = opts.id;
  847. opts.id = function (e) { return e[idKey]; };
  848. }
  849. if ($.isArray(opts.element.data("select2Tags"))) {
  850. if ("tags" in opts) {
  851. throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
  852. }
  853. opts.tags=opts.element.data("select2Tags");
  854. }
  855. if (select) {
  856. opts.query = this.bind(function (query) {
  857. var data = { results: [], more: false },
  858. term = query.term,
  859. children, placeholderOption, process;
  860. process=function(element, collection) {
  861. var group;
  862. if (element.is("option")) {
  863. if (query.matcher(term, element.text(), element)) {
  864. collection.push(self.optionToData(element));
  865. }
  866. } else if (element.is("optgroup")) {
  867. group=self.optionToData(element);
  868. element.children().each2(function(i, elm) { process(elm, group.children); });
  869. if (group.children.length>0) {
  870. collection.push(group);
  871. }
  872. }
  873. };
  874. children=element.children();
  875. // ignore the placeholder option if there is one
  876. if (this.getPlaceholder() !== undefined && children.length > 0) {
  877. placeholderOption = this.getPlaceholderOption();
  878. if (placeholderOption) {
  879. children=children.not(placeholderOption);
  880. }
  881. }
  882. children.each2(function(i, elm) { process(elm, data.results); });
  883. query.callback(data);
  884. });
  885. // this is needed because inside val() we construct choices from options and their id is hardcoded
  886. opts.id=function(e) { return e.id; };
  887. } else {
  888. if (!("query" in opts)) {
  889. if ("ajax" in opts) {
  890. ajaxUrl = opts.element.data("ajax-url");
  891. if (ajaxUrl && ajaxUrl.length > 0) {
  892. opts.ajax.url = ajaxUrl;
  893. }
  894. opts.query = ajax.call(opts.element, opts.ajax);
  895. } else if ("data" in opts) {
  896. opts.query = local(opts.data);
  897. } else if ("tags" in opts) {
  898. opts.query = tags(opts.tags);
  899. if (opts.createSearchChoice === undefined) {
  900. opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; };
  901. }
  902. if (opts.initSelection === undefined) {
  903. opts.initSelection = function (element, callback) {
  904. var data = [];
  905. $(splitVal(element.val(), opts.separator, opts.transformVal)).each(function () {
  906. var obj = { id: this, text: this },
  907. tags = opts.tags;
  908. if ($.isFunction(tags)) tags=tags();
  909. $(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } });
  910. data.push(obj);
  911. });
  912. callback(data);
  913. };
  914. }
  915. }
  916. }
  917. }
  918. if (typeof(opts.query) !== "function") {
  919. throw "query function not defined for Select2 " + opts.element.attr("id");
  920. }
  921. if (opts.createSearchChoicePosition === 'top') {
  922. opts.createSearchChoicePosition = function(list, item) { list.unshift(item); };
  923. }
  924. else if (opts.createSearchChoicePosition === 'bottom') {
  925. opts.createSearchChoicePosition = function(list, item) { list.push(item); };
  926. }
  927. else if (typeof(opts.createSearchChoicePosition) !== "function") {
  928. throw "invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function";
  929. }
  930. return opts;
  931. },
  932. /**
  933. * Monitor the original element for changes and update select2 accordingly
  934. */
  935. // abstract
  936. monitorSource: function () {
  937. var el = this.opts.element, observer, self = this;
  938. el.on("change.select2", this.bind(function (e) {
  939. if (this.opts.element.data("select2-change-triggered") !== true) {
  940. this.initSelection();
  941. }
  942. }));
  943. this._sync = this.bind(function () {
  944. // sync enabled state
  945. var disabled = el.prop("disabled");
  946. if (disabled === undefined) disabled = false;
  947. this.enable(!disabled);
  948. var readonly = el.prop("readonly");
  949. if (readonly === undefined) readonly = false;
  950. this.readonly(readonly);
  951. if (this.container) {
  952. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  953. this.container.addClass(evaluate(this.opts.containerCssClass, this.opts.element));
  954. }
  955. if (this.dropdown) {
  956. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  957. this.dropdown.addClass(evaluate(this.opts.dropdownCssClass, this.opts.element));
  958. }
  959. });
  960. // IE8-10 (IE9/10 won't fire propertyChange via attachEventListener)
  961. if (el.length && el[0].attachEvent) {
  962. el.each(function() {
  963. this.attachEvent("onpropertychange", self._sync);
  964. });
  965. }
  966. // safari, chrome, firefox, IE11
  967. observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver;
  968. if (observer !== undefined) {
  969. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  970. this.propertyObserver = new observer(function (mutations) {
  971. $.each(mutations, self._sync);
  972. });
  973. this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
  974. }
  975. },
  976. // abstract
  977. triggerSelect: function(data) {
  978. var evt = $.Event("select2-selecting", { val: this.id(data), object: data, choice: data });
  979. this.opts.element.trigger(evt);
  980. return !evt.isDefaultPrevented();
  981. },
  982. /**
  983. * Triggers the change event on the source element
  984. */
  985. // abstract
  986. triggerChange: function (details) {
  987. details = details || {};
  988. details= $.extend({}, details, { type: "change", val: this.val() });
  989. // prevents recursive triggering
  990. this.opts.element.data("select2-change-triggered", true);
  991. this.opts.element.trigger(details);
  992. this.opts.element.data("select2-change-triggered", false);
  993. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  994. // so here we trigger the click event manually
  995. this.opts.element.click();
  996. // ValidationEngine ignores the change event and listens instead to blur
  997. // so here we trigger the blur event manually if so desired
  998. if (this.opts.blurOnChange)
  999. this.opts.element.blur();
  1000. },
  1001. //abstract
  1002. isInterfaceEnabled: function()
  1003. {
  1004. return this.enabledInterface === true;
  1005. },
  1006. // abstract
  1007. enableInterface: function() {
  1008. var enabled = this._enabled && !this._readonly,
  1009. disabled = !enabled;
  1010. if (enabled === this.enabledInterface) return false;
  1011. this.container.toggleClass("select2-container-disabled", disabled);
  1012. this.close();
  1013. this.enabledInterface = enabled;
  1014. return true;
  1015. },
  1016. // abstract
  1017. enable: function(enabled) {
  1018. if (enabled === undefined) enabled = true;
  1019. if (this._enabled === enabled) return;
  1020. this._enabled = enabled;
  1021. this.opts.element.prop("disabled", !enabled);
  1022. this.enableInterface();
  1023. },
  1024. // abstract
  1025. disable: function() {
  1026. this.enable(false);
  1027. },
  1028. // abstract
  1029. readonly: function(enabled) {
  1030. if (enabled === undefined) enabled = false;
  1031. if (this._readonly === enabled) return;
  1032. this._readonly = enabled;
  1033. this.opts.element.prop("readonly", enabled);
  1034. this.enableInterface();
  1035. },
  1036. // abstract
  1037. opened: function () {
  1038. return (this.container) ? this.container.hasClass("select2-dropdown-open") : false;
  1039. },
  1040. // abstract
  1041. positionDropdown: function() {
  1042. var $dropdown = this.dropdown,
  1043. container = this.container,
  1044. offset = container.offset(),
  1045. height = container.outerHeight(false),
  1046. width = container.outerWidth(false),
  1047. dropHeight = $dropdown.outerHeight(false),
  1048. $window = $(window),
  1049. windowWidth = $window.width(),
  1050. windowHeight = $window.height(),
  1051. viewPortRight = $window.scrollLeft() + windowWidth,
  1052. viewportBottom = $window.scrollTop() + windowHeight,
  1053. dropTop = offset.top + height,
  1054. dropLeft = offset.left,
  1055. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  1056. enoughRoomAbove = (offset.top - dropHeight) >= $window.scrollTop(),
  1057. dropWidth = $dropdown.outerWidth(false),
  1058. enoughRoomOnRight = function() {
  1059. return dropLeft + dropWidth <= viewPortRight;
  1060. },
  1061. enoughRoomOnLeft = function() {
  1062. return offset.left + viewPortRight + container.outerWidth(false) > dropWidth;
  1063. },
  1064. aboveNow = $dropdown.hasClass("select2-drop-above"),
  1065. bodyOffset,
  1066. above,
  1067. changeDirection,
  1068. css,
  1069. resultsListNode;
  1070. // always prefer the current above/below alignment, unless there is not enough room
  1071. if (aboveNow) {
  1072. above = true;
  1073. if (!enoughRoomAbove && enoughRoomBelow) {
  1074. changeDirection = true;
  1075. above = false;
  1076. }
  1077. } else {
  1078. above = false;
  1079. if (!enoughRoomBelow && enoughRoomAbove) {
  1080. changeDirection = true;
  1081. above = true;
  1082. }
  1083. }
  1084. //if we are changing direction we need to get positions when dropdown is hidden;
  1085. if (changeDirection) {
  1086. $dropdown.hide();
  1087. offset = this.container.offset();
  1088. height = this.container.outerHeight(false);
  1089. width = this.container.outerWidth(false);
  1090. dropHeight = $dropdown.outerHeight(false);
  1091. viewPortRight = $window.scrollLeft() + windowWidth;
  1092. viewportBottom = $window.scrollTop() + windowHeight;
  1093. dropTop = offset.top + height;
  1094. dropLeft = offset.left;
  1095. dropWidth = $dropdown.outerWidth(false);
  1096. $dropdown.show();
  1097. // fix so the cursor does not move to the left within the search-textbox in IE
  1098. this.focusSearch();
  1099. }
  1100. if (this.opts.dropdownAutoWidth) {
  1101. resultsListNode = $('.select2-results', $dropdown)[0];
  1102. $dropdown.addClass('select2-drop-auto-width');
  1103. $dropdown.css('width', '');
  1104. // Add scrollbar width to dropdown if vertical scrollbar is present
  1105. dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
  1106. dropWidth > width ? width = dropWidth : dropWidth = width;
  1107. dropHeight = $dropdown.outerHeight(false);
  1108. }
  1109. else {
  1110. this.container.removeClass('select2-drop-auto-width');
  1111. }
  1112. //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  1113. //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body.scrollTop(), "enough?", enoughRoomAbove);
  1114. // fix positioning when body has an offset and is not position: static
  1115. if (this.body.css('position') !== 'static') {
  1116. bodyOffset = this.body.offset();
  1117. dropTop -= bodyOffset.top;
  1118. dropLeft -= bodyOffset.left;
  1119. }
  1120. if (!enoughRoomOnRight() && enoughRoomOnLeft()) {
  1121. dropLeft = offset.left + this.container.outerWidth(false) - dropWidth;
  1122. }
  1123. css = {
  1124. left: dropLeft,
  1125. width: width
  1126. };
  1127. if (above) {
  1128. css.top = offset.top - dropHeight;
  1129. css.bottom = 'auto';
  1130. this.container.addClass("select2-drop-above");
  1131. $dropdown.addClass("select2-drop-above");
  1132. }
  1133. else {
  1134. css.top = dropTop;
  1135. css.bottom = 'auto';
  1136. this.container.removeClass("select2-drop-above");
  1137. $dropdown.removeClass("select2-drop-above");
  1138. }
  1139. css = $.extend(css, evaluate(this.opts.dropdownCss, this.opts.element));
  1140. $dropdown.css(css);
  1141. },
  1142. // abstract
  1143. shouldOpen: function() {
  1144. var event;
  1145. if (this.opened()) return false;
  1146. if (this._enabled === false || this._readonly === true) return false;
  1147. event = $.Event("select2-opening");
  1148. this.opts.element.trigger(event);
  1149. return !event.isDefaultPrevented();
  1150. },
  1151. // abstract
  1152. clearDropdownAlignmentPreference: function() {
  1153. // clear the classes used to figure out the preference of where the dropdown should be opened
  1154. this.container.removeClass("select2-drop-above");
  1155. this.dropdown.removeClass("select2-drop-above");
  1156. },
  1157. /**
  1158. * Opens the dropdown
  1159. *
  1160. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  1161. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  1162. */
  1163. // abstract
  1164. open: function () {
  1165. if (!this.shouldOpen()) return false;
  1166. this.opening();
  1167. // Only bind the document mousemove when the dropdown is visible
  1168. $document.on("mousemove.select2Event", function (e) {
  1169. lastMousePosition.x = e.pageX;
  1170. lastMousePosition.y = e.pageY;
  1171. });
  1172. return true;
  1173. },
  1174. /**
  1175. * Performs the opening of the dropdown
  1176. */
  1177. // abstract
  1178. opening: function() {
  1179. var cid = this.containerEventName,
  1180. scroll = "scroll." + cid,
  1181. resize = "resize."+cid,
  1182. orient = "orientationchange."+cid,
  1183. mask;
  1184. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  1185. this.clearDropdownAlignmentPreference();
  1186. if(this.dropdown[0] !== this.body.children().last()[0]) {
  1187. this.dropdown.detach().appendTo(this.body);
  1188. }
  1189. // create the dropdown mask if doesn't already exist
  1190. mask = $("#select2-drop-mask");
  1191. if (mask.length === 0) {
  1192. mask = $(document.createElement("div"));
  1193. mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
  1194. mask.hide();
  1195. mask.appendTo(this.body);
  1196. mask.on("mousedown touchstart click", function (e) {
  1197. // Prevent IE from generating a click event on the body
  1198. reinsertElement(mask);
  1199. var dropdown = $("#select2-drop"), self;
  1200. if (dropdown.length > 0) {
  1201. self=dropdown.data("select2");
  1202. if (self.opts.selectOnBlur) {
  1203. self.selectHighlighted({noFocus: true});
  1204. }
  1205. self.close();
  1206. e.preventDefault();
  1207. e.stopPropagation();
  1208. }
  1209. });
  1210. }
  1211. // ensure the mask is always right before the dropdown
  1212. if (this.dropdown.prev()[0] !== mask[0]) {
  1213. this.dropdown.before(mask);
  1214. }
  1215. // move the global id to the correct dropdown
  1216. $("#select2-drop").removeAttr("id");
  1217. this.dropdown.attr("id", "select2-drop");
  1218. // show the elements
  1219. mask.show();
  1220. this.positionDropdown();
  1221. this.dropdown.show();
  1222. this.positionDropdown();
  1223. this.dropdown.addClass("select2-drop-active");
  1224. // attach listeners to events that can change the position of the container and thus require
  1225. // the position of the dropdown to be updated as well so it does not come unglued from the container
  1226. var that = this;
  1227. this.container.parents().add(window).each(function () {
  1228. $(this).on(resize+" "+scroll+" "+orient, function (e) {
  1229. if (that.opened()) that.positionDropdown();
  1230. });
  1231. });
  1232. },
  1233. // abstract
  1234. close: function () {
  1235. if (!this.opened()) return;
  1236. var cid = this.containerEventName,
  1237. scroll = "scroll." + cid,
  1238. resize = "resize."+cid,
  1239. orient = "orientationchange."+cid;
  1240. // unbind event listeners
  1241. this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });
  1242. this.clearDropdownAlignmentPreference();
  1243. $("#select2-drop-mask").hide();
  1244. this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
  1245. this.dropdown.hide();
  1246. this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
  1247. this.results.empty();
  1248. // Now that the dropdown is closed, unbind the global document mousemove event
  1249. $document.off("mousemove.select2Event");
  1250. this.clearSearch();
  1251. this.search.removeClass("select2-active");
  1252. this.opts.element.trigger($.Event("select2-close"));
  1253. },
  1254. /**
  1255. * Opens control, sets input value, and updates results.
  1256. */
  1257. // abstract
  1258. externalSearch: function (term) {
  1259. this.open();
  1260. this.search.val(term);
  1261. this.updateResults(false);
  1262. },
  1263. // abstract
  1264. clearSearch: function () {
  1265. },
  1266. //abstract
  1267. getMaximumSelectionSize: function() {
  1268. return evaluate(this.opts.maximumSelectionSize, this.opts.element);
  1269. },
  1270. // abstract
  1271. ensureHighlightVisible: function () {
  1272. var results = this.results, children, index, child, hb, rb, y, more, topOffset;
  1273. index = this.highlight();
  1274. if (index < 0) return;
  1275. if (index == 0) {
  1276. // if the first element is highlighted scroll all the way to the top,
  1277. // that way any unselectable headers above it will also be scrolled
  1278. // into view
  1279. results.scrollTop(0);
  1280. return;
  1281. }
  1282. children = this.findHighlightableChoices().find('.select2-result-label');
  1283. child = $(children[index]);
  1284. topOffset = (child.offset() || {}).top || 0;
  1285. hb = topOffset + child.outerHeight(true);
  1286. // if this is the last child lets also make sure select2-more-results is visible
  1287. if (index === children.length - 1) {
  1288. more = results.find("li.select2-more-results");
  1289. if (more.length > 0) {
  1290. hb = more.offset().top + more.outerHeight(true);
  1291. }
  1292. }
  1293. rb = results.offset().top + results.outerHeight(false);
  1294. if (hb > rb) {
  1295. results.scrollTop(results.scrollTop() + (hb - rb));
  1296. }
  1297. y = topOffset - results.offset().top;
  1298. // make sure the top of the element is visible
  1299. if (y < 0 && child.css('display') != 'none' ) {
  1300. results.scrollTop(results.scrollTop() + y); // y is negative
  1301. }
  1302. },
  1303. // abstract
  1304. findHighlightableChoices: function() {
  1305. return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)");
  1306. },
  1307. // abstract
  1308. moveHighlight: function (delta) {
  1309. var choices = this.findHighlightableChoices(),
  1310. index = this.highlight();
  1311. while (index > -1 && index < choices.length) {
  1312. index += delta;
  1313. var choice = $(choices[index]);
  1314. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
  1315. this.highlight(index);
  1316. break;
  1317. }
  1318. }
  1319. },
  1320. // abstract
  1321. highlight: function (index) {
  1322. var choices = this.findHighlightableChoices(),
  1323. choice,
  1324. data;
  1325. if (arguments.length === 0) {
  1326. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  1327. }
  1328. if (index >= choices.length) index = choices.length - 1;
  1329. if (index < 0) index = 0;
  1330. this.removeHighlight();
  1331. choice = $(choices[index]);
  1332. choice.addClass("select2-highlighted");
  1333. // ensure assistive technology can determine the active choice
  1334. this.search.attr("aria-activedescendant", choice.find(".select2-result-label").attr("id"));
  1335. this.ensureHighlightVisible();
  1336. this.liveRegion.text(choice.text());
  1337. data = choice.data("select2-data");
  1338. if (data) {
  1339. this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
  1340. }
  1341. },
  1342. removeHighlight: function() {
  1343. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1344. },
  1345. touchMoved: function() {
  1346. this._touchMoved = true;
  1347. },
  1348. clearTouchMoved: function() {
  1349. this._touchMoved = false;
  1350. },
  1351. // abstract
  1352. countSelectableResults: function() {
  1353. return this.findHighlightableChoices().length;
  1354. },
  1355. // abstract
  1356. highlightUnderEvent: function (event) {
  1357. var el = $(event.target).closest(".select2-result-selectable");
  1358. if (el.length > 0 && !el.is(".select2-highlighted")) {
  1359. var choices = this.findHighlightableChoices();
  1360. this.highlight(choices.index(el));
  1361. } else if (el.length == 0) {
  1362. // if we are over an unselectable item remove all highlights
  1363. this.removeHighlight();
  1364. }
  1365. },
  1366. // abstract
  1367. loadMoreIfNeeded: function () {
  1368. var results = this.results,
  1369. more = results.find("li.select2-more-results"),
  1370. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  1371. page = this.resultsPage + 1,
  1372. self=this,
  1373. term=this.search.val(),
  1374. context=this.context;
  1375. if (more.length === 0) return;
  1376. below = more.offset().top - results.offset().top - results.height();
  1377. if (below <= this.opts.loadMorePadding) {
  1378. more.addClass("select2-active");
  1379. this.opts.query({
  1380. element: this.opts.element,
  1381. term: term,
  1382. page: page,
  1383. context: context,
  1384. matcher: this.opts.matcher,
  1385. callback: this.bind(function (data) {
  1386. // ignore a response if the select2 has been closed before it was received
  1387. if (!self.opened()) return;
  1388. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  1389. self.postprocessResults(data, false, false);
  1390. if (data.more===true) {
  1391. more.detach().appendTo(results).html(self.opts.escapeMarkup(evaluate(self.opts.formatLoadMore, self.opts.element, page+1)));
  1392. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1393. } else {
  1394. more.remove();
  1395. }
  1396. self.positionDropdown();
  1397. self.resultsPage = page;
  1398. self.context = data.context;
  1399. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1400. })});
  1401. }
  1402. },
  1403. /**
  1404. * Default tokenizer function which does nothing
  1405. */
  1406. tokenize: function() {
  1407. },
  1408. /**
  1409. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  1410. */
  1411. // abstract
  1412. updateResults: function (initial) {
  1413. var search = this.search,
  1414. results = this.results,
  1415. opts = this.opts,
  1416. data,
  1417. self = this,
  1418. input,
  1419. term = search.val(),
  1420. lastTerm = $.data(this.container, "select2-last-term"),
  1421. // sequence number used to drop out-of-order responses
  1422. queryNumber;
  1423. // prevent duplicate queries against the same term
  1424. if (initial !== true && lastTerm && equal(term, lastTerm)) return;
  1425. $.data(this.container, "select2-last-term", term);
  1426. // if the search is currently hidden we do not alter the results
  1427. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  1428. return;
  1429. }
  1430. function postRender() {
  1431. search.removeClass("select2-active");
  1432. self.positionDropdown();
  1433. if (results.find('.select2-no-results,.select2-selection-limit,.select2-searching').length) {
  1434. self.liveRegion.text(results.text());
  1435. }
  1436. else {
  1437. self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable:not(".select2-selected")').length));
  1438. }
  1439. }
  1440. function render(html) {
  1441. results.html(html);
  1442. postRender();
  1443. }
  1444. queryNumber = ++this.queryCount;
  1445. var maxSelSize = this.getMaximumSelectionSize();
  1446. if (maxSelSize >=1) {
  1447. data = this.data();
  1448. if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  1449. render("<li class='select2-selection-limit'>" + evaluate(opts.formatSelectionTooBig, opts.element, maxSelSize) + "</li>");
  1450. return;
  1451. }
  1452. }
  1453. if (search.val().length < opts.minimumInputLength) {
  1454. if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  1455. render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooShort, opts.element, search.val(), opts.minimumInputLength) + "</li>");
  1456. } else {
  1457. render("");
  1458. }
  1459. if (initial && this.showSearch) this.showSearch(true);
  1460. return;
  1461. }
  1462. if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
  1463. if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
  1464. render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooLong, opts.element, search.val(), opts.maximumInputLength) + "</li>");
  1465. } else {
  1466. render("");
  1467. }
  1468. return;
  1469. }
  1470. if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
  1471. render("<li class='select2-searching'>" + evaluate(opts.formatSearching, opts.element) + "</li>");
  1472. }
  1473. search.addClass("select2-active");
  1474. this.removeHighlight();
  1475. // give the tokenizer a chance to pre-process the input
  1476. input = this.tokenize();
  1477. if (input != undefined && input != null) {
  1478. search.val(input);
  1479. }
  1480. this.resultsPage = 1;
  1481. opts.query({
  1482. element: opts.element,
  1483. term: search.val(),
  1484. page: this.resultsPage,
  1485. context: null,
  1486. matcher: opts.matcher,
  1487. callback: this.bind(function (data) {
  1488. var def; // default choice
  1489. // ignore old responses
  1490. if (queryNumber != this.queryCount) {
  1491. return;
  1492. }
  1493. // ignore a response if the select2 has been closed before it was received
  1494. if (!this.opened()) {
  1495. this.search.removeClass("select2-active");
  1496. return;
  1497. }
  1498. // handle ajax error
  1499. if(data.hasError !== undefined && checkFormatter(opts.formatAjaxError, "formatAjaxError")) {
  1500. render("<li class='select2-ajax-error'>" + evaluate(opts.formatAjaxError, opts.element, data.jqXHR, data.textStatus, data.errorThrown) + "</li>");
  1501. return;
  1502. }
  1503. // save context, if any
  1504. this.context = (data.context===undefined) ? null : data.context;
  1505. // create a default choice and prepend it to the list
  1506. if (this.opts.createSearchChoice && search.val() !== "") {
  1507. def = this.opts.createSearchChoice.call(self, search.val(), data.results);
  1508. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  1509. if ($(data.results).filter(
  1510. function () {
  1511. return equal(self.id(this), self.id(def));
  1512. }).length === 0) {
  1513. this.opts.createSearchChoicePosition(data.results, def);
  1514. }
  1515. }
  1516. }
  1517. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  1518. render("<li class='select2-no-results'>" + evaluate(opts.formatNoMatches, opts.element, search.val()) + "</li>");
  1519. return;
  1520. }
  1521. results.empty();
  1522. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  1523. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  1524. results.append("<li class='select2-more-results'>" + opts.escapeMarkup(evaluate(opts.formatLoadMore, opts.element, this.resultsPage)) + "</li>");
  1525. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1526. }
  1527. this.postprocessResults(data, initial);
  1528. postRender();
  1529. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1530. })});
  1531. },
  1532. // abstract
  1533. cancel: function () {
  1534. this.close();
  1535. },
  1536. // abstract
  1537. blur: function () {
  1538. // if selectOnBlur == true, select the currently highlighted option
  1539. if (this.opts.selectOnBlur)
  1540. this.selectHighlighted({noFocus: true});
  1541. this.close();
  1542. this.container.removeClass("select2-container-active");
  1543. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  1544. if (this.search[0] === document.activeElement) { this.search.blur(); }
  1545. this.clearSearch();
  1546. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1547. },
  1548. // abstract
  1549. focusSearch: function () {
  1550. focus(this.search);
  1551. },
  1552. // abstract
  1553. selectHighlighted: function (options) {
  1554. if (this._touchMoved) {
  1555. this.clearTouchMoved();
  1556. return;
  1557. }
  1558. var index=this.highlight(),
  1559. highlighted=this.results.find(".select2-highlighted"),
  1560. data = highlighted.closest('.select2-result').data("select2-data");
  1561. if (data) {
  1562. this.highlight(index);
  1563. this.onSelect(data, options);
  1564. } else if (options && options.noFocus) {
  1565. this.close();
  1566. }
  1567. },
  1568. // abstract
  1569. getPlaceholder: function () {
  1570. var placeholderOption;
  1571. return this.opts.element.attr("placeholder") ||
  1572. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1573. this.opts.element.data("placeholder") ||
  1574. this.opts.placeholder ||
  1575. ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
  1576. },
  1577. // abstract
  1578. getPlaceholderOption: function() {
  1579. if (this.select) {
  1580. var firstOption = this.select.children('option').first();
  1581. if (this.opts.placeholderOption !== undefined ) {
  1582. //Determine the placeholder option based on the specified placeholderOption setting
  1583. return (this.opts.placeholderOption === "first" && firstOption) ||
  1584. (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
  1585. } else if ($.trim(firstOption.text()) === "" && firstOption.val() === "") {
  1586. //No explicit placeholder option specified, use the first if it's blank
  1587. return firstOption;
  1588. }
  1589. }
  1590. },
  1591. /**
  1592. * Get the desired width for the container element. This is
  1593. * derived first from option `width` passed to select2, then
  1594. * the inline 'style' on the original element, and finally
  1595. * falls back to the jQuery calculated element width.
  1596. */
  1597. // abstract
  1598. initContainerWidth: function () {
  1599. function resolveContainerWidth() {
  1600. var style, attrs, matches, i, l, attr;
  1601. if (this.opts.width === "off") {
  1602. return null;
  1603. } else if (this.opts.width === "element"){
  1604. return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
  1605. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1606. // check if there is inline style on the element that contains width
  1607. style = this.opts.element.attr('style');
  1608. if (style !== undefined) {
  1609. attrs = style.split(';');
  1610. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1611. attr = attrs[i].replace(/\s/g, '');
  1612. matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
  1613. if (matches !== null && matches.length >= 1)
  1614. return matches[1];
  1615. }
  1616. }
  1617. if (this.opts.width === "resolve") {
  1618. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1619. // when attached to input type=hidden or elements hidden via css
  1620. style = this.opts.element.css('width');
  1621. if (style.indexOf("%") > 0) return style;
  1622. // finally, fallback on the calculated width of the element
  1623. return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
  1624. }
  1625. return null;
  1626. } else if ($.isFunction(this.opts.width)) {
  1627. return this.opts.width();
  1628. } else {
  1629. return this.opts.width;
  1630. }
  1631. };
  1632. var width = resolveContainerWidth.call(this);
  1633. if (width !== null) {
  1634. this.container.css("width", width);
  1635. }
  1636. }
  1637. });
  1638. SingleSelect2 = clazz(AbstractSelect2, {
  1639. // single
  1640. createContainer: function () {
  1641. var container = $(document.createElement("div")).attr({
  1642. "class": "select2-container"
  1643. }).html([
  1644. "<a href='javascript:void(0)' class='select2-choice' tabindex='-1'>",
  1645. " <span class='select2-chosen'>&#160;</span><abbr class='select2-search-choice-close'></abbr>",
  1646. " <span class='select2-arrow' role='presentation'><b role='presentation'></b></span>",
  1647. "</a>",
  1648. "<label for='' class='select2-offscreen'></label>",
  1649. "<input class='select2-focusser select2-offscreen' type='text' aria-haspopup='true' role='button' />",
  1650. "<div class='select2-drop select2-display-none'>",
  1651. " <div class='select2-search'>",
  1652. " <label for='' class='select2-offscreen'></label>",
  1653. " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' role='combobox' aria-expanded='true'",
  1654. " aria-autocomplete='list' />",
  1655. " </div>",
  1656. " <ul class='select2-results' role='listbox'>",
  1657. " </ul>",
  1658. "</div>"].join(""));
  1659. return container;
  1660. },
  1661. // single
  1662. enableInterface: function() {
  1663. if (this.parent.enableInterface.apply(this, arguments)) {
  1664. this.focusser.prop("disabled", !this.isInterfaceEnabled());
  1665. }
  1666. },
  1667. // single
  1668. opening: function () {
  1669. var el, range, len;
  1670. if (this.opts.minimumResultsForSearch >= 0) {
  1671. this.showSearch(true);
  1672. }
  1673. this.parent.opening.apply(this, arguments);
  1674. if (this.showSearchInput !== false) {
  1675. // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
  1676. // all other browsers handle this just fine
  1677. this.search.val(this.focusser.val());
  1678. }
  1679. if (this.opts.shouldFocusInput(this)) {
  1680. this.search.focus();
  1681. // move the cursor to the end after focussing, otherwise it will be at the beginning and
  1682. // new text will appear *before* focusser.val()
  1683. el = this.search.get(0);
  1684. if (el.createTextRange) {
  1685. range = el.createTextRange();
  1686. range.collapse(false);
  1687. range.select();
  1688. } else if (el.setSelectionRange) {
  1689. len = this.search.val().length;
  1690. el.setSelectionRange(len, len);
  1691. }
  1692. }
  1693. // initializes search's value with nextSearchTerm (if defined by user)
  1694. // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
  1695. if(this.search.val() === "") {
  1696. if(this.nextSearchTerm != undefined){
  1697. this.search.val(this.nextSearchTerm);
  1698. this.search.select();
  1699. }
  1700. }
  1701. this.focusser.prop("disabled", true).val("");
  1702. this.updateResults(true);
  1703. this.opts.element.trigger($.Event("select2-open"));
  1704. },
  1705. // single
  1706. close: function () {
  1707. if (!this.opened()) return;
  1708. this.parent.close.apply(this, arguments);
  1709. this.focusser.prop("disabled", false);
  1710. if (this.opts.shouldFocusInput(this)) {
  1711. this.focusser.focus();
  1712. }
  1713. },
  1714. // single
  1715. focus: function () {
  1716. if (this.opened()) {
  1717. this.close();
  1718. } else {
  1719. this.focusser.prop("disabled", false);
  1720. if (this.opts.shouldFocusInput(this)) {
  1721. this.focusser.focus();
  1722. }
  1723. }
  1724. },
  1725. // single
  1726. isFocused: function () {
  1727. return this.container.hasClass("select2-container-active");
  1728. },
  1729. // single
  1730. cancel: function () {
  1731. this.parent.cancel.apply(this, arguments);
  1732. this.focusser.prop("disabled", false);
  1733. if (this.opts.shouldFocusInput(this)) {
  1734. this.focusser.focus();
  1735. }
  1736. },
  1737. // single
  1738. destroy: function() {
  1739. $("label[for='" + this.focusser.attr('id') + "']")
  1740. .attr('for', this.opts.element.attr("id"));
  1741. this.parent.destroy.apply(this, arguments);
  1742. cleanupJQueryElements.call(this,
  1743. "selection",
  1744. "focusser"
  1745. );
  1746. },
  1747. // single
  1748. initContainer: function () {
  1749. var selection,
  1750. container = this.container,
  1751. dropdown = this.dropdown,
  1752. idSuffix = nextUid(),
  1753. elementLabel;
  1754. if (this.opts.minimumResultsForSearch < 0) {
  1755. this.showSearch(false);
  1756. } else {
  1757. this.showSearch(true);
  1758. }
  1759. this.selection = selection = container.find(".select2-choice");
  1760. this.focusser = container.find(".select2-focusser");
  1761. // add aria associations
  1762. selection.find(".select2-chosen").attr("id", "select2-chosen-"+idSuffix);
  1763. this.focusser.attr("aria-labelledby", "select2-chosen-"+idSuffix);
  1764. this.results.attr("id", "select2-results-"+idSuffix);
  1765. this.search.attr("aria-owns", "select2-results-"+idSuffix);
  1766. // rewrite labels from original element to focusser
  1767. this.focusser.attr("id", "s2id_autogen"+idSuffix);
  1768. elementLabel = $("label[for='" + this.opts.element.attr("id") + "']");
  1769. this.opts.element.focus(this.bind(function () { this.focus(); }));
  1770. this.focusser.prev()
  1771. .text(elementLabel.text())
  1772. .attr('for', this.focusser.attr('id'));
  1773. // Ensure the original element retains an accessible name
  1774. var originalTitle = this.opts.element.attr("title");
  1775. this.opts.element.attr("title", (originalTitle || elementLabel.text()));
  1776. this.focusser.attr("tabindex", this.elementTabIndex);
  1777. // write label for search field using the label from the focusser element
  1778. this.search.attr("id", this.focusser.attr('id') + '_search');
  1779. this.search.prev()
  1780. .text($("label[for='" + this.focusser.attr('id') + "']").text())
  1781. .attr('for', this.search.attr('id'));
  1782. this.search.on("keydown", this.bind(function (e) {
  1783. if (!this.isInterfaceEnabled()) return;
  1784. // filter 229 keyCodes (input method editor is processing key input)
  1785. if (229 == e.keyCode) return;
  1786. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1787. // prevent the page from scrolling
  1788. killEvent(e);
  1789. return;
  1790. }
  1791. switch (e.which) {
  1792. case KEY.UP:
  1793. case KEY.DOWN:
  1794. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1795. killEvent(e);
  1796. return;
  1797. case KEY.ENTER:
  1798. this.selectHighlighted();
  1799. killEvent(e);
  1800. return;
  1801. case KEY.TAB:
  1802. this.selectHighlighted({noFocus: true});
  1803. return;
  1804. case KEY.ESC:
  1805. this.cancel(e);
  1806. killEvent(e);
  1807. return;
  1808. }
  1809. }));
  1810. this.search.on("blur", this.bind(function(e) {
  1811. // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
  1812. // without this the search field loses focus which is annoying
  1813. if (document.activeElement === this.body.get(0)) {
  1814. window.setTimeout(this.bind(function() {
  1815. if (this.opened()) {
  1816. this.search.focus();
  1817. }
  1818. }), 0);
  1819. }
  1820. }));
  1821. this.focusser.on("keydown", this.bind(function (e) {
  1822. if (!this.isInterfaceEnabled()) return;
  1823. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1824. return;
  1825. }
  1826. if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
  1827. killEvent(e);
  1828. return;
  1829. }
  1830. if (e.which == KEY.DOWN || e.which == KEY.UP
  1831. || (e.which == KEY.ENTER && this.opts.openOnEnter)) {
  1832. if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;
  1833. this.open();
  1834. killEvent(e);
  1835. return;
  1836. }
  1837. if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
  1838. if (this.opts.allowClear) {
  1839. this.clear();
  1840. }
  1841. killEvent(e);
  1842. return;
  1843. }
  1844. }));
  1845. installKeyUpChangeEvent(this.focusser);
  1846. this.focusser.on("keyup-change input", this.bind(function(e) {
  1847. if (this.opts.minimumResultsForSearch >= 0) {
  1848. e.stopPropagation();
  1849. if (this.opened()) return;
  1850. this.open();
  1851. }
  1852. }));
  1853. selection.on("mousedown touchstart", "abbr", this.bind(function (e) {
  1854. if (!this.isInterfaceEnabled()) {
  1855. return;
  1856. }
  1857. this.clear();
  1858. killEventImmediately(e);
  1859. this.close();
  1860. if (this.selection) {
  1861. this.selection.focus();
  1862. }
  1863. }));
  1864. selection.on("mousedown touchstart", this.bind(function (e) {
  1865. // Prevent IE from generating a click event on the body
  1866. reinsertElement(selection);
  1867. if (!this.container.hasClass("select2-container-active")) {
  1868. this.opts.element.trigger($.Event("select2-focus"));
  1869. }
  1870. if (this.opened()) {
  1871. this.close();
  1872. } else if (this.isInterfaceEnabled()) {
  1873. this.open();
  1874. }
  1875. killEvent(e);
  1876. }));
  1877. dropdown.on("mousedown touchstart", this.bind(function() {
  1878. if (this.opts.shouldFocusInput(this)) {
  1879. this.search.focus();
  1880. }
  1881. }));
  1882. selection.on("focus", this.bind(function(e) {
  1883. killEvent(e);
  1884. }));
  1885. this.focusser.on("focus", this.bind(function(){
  1886. if (!this.container.hasClass("select2-container-active")) {
  1887. this.opts.element.trigger($.Event("select2-focus"));
  1888. }
  1889. this.container.addClass("select2-container-active");
  1890. })).on("blur", this.bind(function() {
  1891. if (!this.opened()) {
  1892. this.container.removeClass("select2-container-active");
  1893. this.opts.element.trigger($.Event("select2-blur"));
  1894. }
  1895. }));
  1896. this.search.on("focus", this.bind(function(){
  1897. if (!this.container.hasClass("select2-container-active")) {
  1898. this.opts.element.trigger($.Event("select2-focus"));
  1899. }
  1900. this.container.addClass("select2-container-active");
  1901. }));
  1902. this.initContainerWidth();
  1903. this.opts.element.hide();
  1904. this.setPlaceholder();
  1905. },
  1906. // single
  1907. clear: function(triggerChange) {
  1908. var data=this.selection.data("select2-data");
  1909. if (data) { // guard against queued quick consecutive clicks
  1910. var evt = $.Event("select2-clearing");
  1911. this.opts.element.trigger(evt);
  1912. if (evt.isDefaultPrevented()) {
  1913. return;
  1914. }
  1915. var placeholderOption = this.getPlaceholderOption();
  1916. this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
  1917. this.selection.find(".select2-chosen").empty();
  1918. this.selection.removeData("select2-data");
  1919. this.setPlaceholder();
  1920. if (triggerChange !== false){
  1921. this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
  1922. this.triggerChange({removed:data});
  1923. }
  1924. }
  1925. },
  1926. /**
  1927. * Sets selection based on source element's value
  1928. */
  1929. // single
  1930. initSelection: function () {
  1931. var selected;
  1932. if (this.isPlaceholderOptionSelected()) {
  1933. this.updateSelection(null);
  1934. this.close();
  1935. this.setPlaceholder();
  1936. } else {
  1937. var self = this;
  1938. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1939. if (selected !== undefined && selected !== null) {
  1940. self.updateSelection(selected);
  1941. self.close();
  1942. self.setPlaceholder();
  1943. self.nextSearchTerm = self.opts.nextSearchTerm(selected, self.search.val());
  1944. }
  1945. });
  1946. }
  1947. },
  1948. isPlaceholderOptionSelected: function() {
  1949. var placeholderOption;
  1950. if (this.getPlaceholder() === undefined) return false; // no placeholder specified so no option should be considered
  1951. return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected"))
  1952. || (this.opts.element.val() === "")
  1953. || (this.opts.element.val() === undefined)
  1954. || (this.opts.element.val() === null);
  1955. },
  1956. // single
  1957. prepareOpts: function () {
  1958. var opts = this.parent.prepareOpts.apply(this, arguments),
  1959. self=this;
  1960. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1961. // install the selection initializer
  1962. opts.initSelection = function (element, callback) {
  1963. var selected = element.find("option").filter(function() { return this.selected && !this.disabled });
  1964. // a single select box always has a value, no need to null check 'selected'
  1965. callback(self.optionToData(selected));
  1966. };
  1967. } else if ("data" in opts) {
  1968. // install default initSelection when applied to hidden input and data is local
  1969. opts.initSelection = opts.initSelection || function (element, callback) {
  1970. var id = element.val();
  1971. //search in data by id, storing the actual matching item
  1972. var match = null;
  1973. opts.query({
  1974. matcher: function(term, text, el){
  1975. var is_match = equal(id, opts.id(el));
  1976. if (is_match) {
  1977. match = el;
  1978. }
  1979. return is_match;
  1980. },
  1981. callback: !$.isFunction(callback) ? $.noop : function() {
  1982. callback(match);
  1983. }
  1984. });
  1985. };
  1986. }
  1987. return opts;
  1988. },
  1989. // single
  1990. getPlaceholder: function() {
  1991. // if a placeholder is specified on a single select without a valid placeholder option ignore it
  1992. if (this.select) {
  1993. if (this.getPlaceholderOption() === undefined) {
  1994. return undefined;
  1995. }
  1996. }
  1997. return this.parent.getPlaceholder.apply(this, arguments);
  1998. },
  1999. // single
  2000. setPlaceholder: function () {
  2001. var placeholder = this.getPlaceholder();
  2002. if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {
  2003. // check for a placeholder option if attached to a select
  2004. if (this.select && this.getPlaceholderOption() === undefined) return;
  2005. this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));
  2006. this.selection.addClass("select2-default");
  2007. this.container.removeClass("select2-allowclear");
  2008. }
  2009. },
  2010. // single
  2011. postprocessResults: function (data, initial, noHighlightUpdate) {
  2012. var selected = 0, self = this, showSearchInput = true;
  2013. // find the selected element in the result list
  2014. this.findHighlightableChoices().each2(function (i, elm) {
  2015. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  2016. selected = i;
  2017. return false;
  2018. }
  2019. });
  2020. // and highlight it
  2021. if (noHighlightUpdate !== false) {
  2022. if (initial === true && selected >= 0) {
  2023. this.highlight(selected);
  2024. } else {
  2025. this.highlight(0);
  2026. }
  2027. }
  2028. // hide the search box if this is the first we got the results and there are enough of them for search
  2029. if (initial === true) {
  2030. var min = this.opts.minimumResultsForSearch;
  2031. if (min >= 0) {
  2032. this.showSearch(countResults(data.results) >= min);
  2033. }
  2034. }
  2035. },
  2036. // single
  2037. showSearch: function(showSearchInput) {
  2038. if (this.showSearchInput === showSearchInput) return;
  2039. this.showSearchInput = showSearchInput;
  2040. this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
  2041. this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
  2042. //add "select2-with-searchbox" to the container if search box is shown
  2043. $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
  2044. },
  2045. // single
  2046. onSelect: function (data, options) {
  2047. if (!this.triggerSelect(data)) { return; }
  2048. var old = this.opts.element.val(),
  2049. oldData = this.data();
  2050. this.opts.element.val(this.id(data));
  2051. this.updateSelection(data);
  2052. this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
  2053. this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
  2054. this.close();
  2055. if ((!options || !options.noFocus) && this.opts.shouldFocusInput(this)) {
  2056. this.focusser.focus();
  2057. }
  2058. if (!equal(old, this.id(data))) {
  2059. this.triggerChange({ added: data, removed: oldData });
  2060. }
  2061. },
  2062. // single
  2063. updateSelection: function (data) {
  2064. var container=this.selection.find(".select2-chosen"), formatted, cssClass;
  2065. this.selection.data("select2-data", data);
  2066. container.empty();
  2067. if (data !== null) {
  2068. formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
  2069. }
  2070. if (formatted !== undefined) {
  2071. container.append(formatted);
  2072. }
  2073. cssClass=this.opts.formatSelectionCssClass(data, container);
  2074. if (cssClass !== undefined) {
  2075. container.addClass(cssClass);
  2076. }
  2077. this.selection.removeClass("select2-default");
  2078. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  2079. this.container.addClass("select2-allowclear");
  2080. }
  2081. },
  2082. // single
  2083. val: function () {
  2084. var val,
  2085. triggerChange = false,
  2086. data = null,
  2087. self = this,
  2088. oldData = this.data();
  2089. if (arguments.length === 0) {
  2090. return this.opts.element.val();
  2091. }
  2092. val = arguments[0];
  2093. if (arguments.length > 1) {
  2094. triggerChange = arguments[1];
  2095. }
  2096. if (this.select) {
  2097. this.select
  2098. .val(val)
  2099. .find("option").filter(function() { return this.selected }).each2(function (i, elm) {
  2100. data = self.optionToData(elm);
  2101. return false;
  2102. });
  2103. this.updateSelection(data);
  2104. this.setPlaceholder();
  2105. if (triggerChange) {
  2106. this.triggerChange({added: data, removed:oldData});
  2107. }
  2108. } else {
  2109. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2110. if (!val && val !== 0) {
  2111. this.clear(triggerChange);
  2112. return;
  2113. }
  2114. if (this.opts.initSelection === undefined) {
  2115. throw new Error("cannot call val() if initSelection() is not defined");
  2116. }
  2117. this.opts.element.val(val);
  2118. this.opts.initSelection(this.opts.element, function(data){
  2119. self.opts.element.val(!data ? "" : self.id(data));
  2120. self.updateSelection(data);
  2121. self.setPlaceholder();
  2122. if (triggerChange) {
  2123. self.triggerChange({added: data, removed:oldData});
  2124. }
  2125. });
  2126. }
  2127. },
  2128. // single
  2129. clearSearch: function () {
  2130. this.search.val("");
  2131. this.focusser.val("");
  2132. },
  2133. // single
  2134. data: function(value) {
  2135. var data,
  2136. triggerChange = false;
  2137. if (arguments.length === 0) {
  2138. data = this.selection.data("select2-data");
  2139. if (data == undefined) data = null;
  2140. return data;
  2141. } else {
  2142. if (arguments.length > 1) {
  2143. triggerChange = arguments[1];
  2144. }
  2145. if (!value) {
  2146. this.clear(triggerChange);
  2147. } else {
  2148. data = this.data();
  2149. this.opts.element.val(!value ? "" : this.id(value));
  2150. this.updateSelection(value);
  2151. if (triggerChange) {
  2152. this.triggerChange({added: value, removed:data});
  2153. }
  2154. }
  2155. }
  2156. }
  2157. });
  2158. MultiSelect2 = clazz(AbstractSelect2, {
  2159. // multi
  2160. createContainer: function () {
  2161. var container = $(document.createElement("div")).attr({
  2162. "class": "select2-container select2-container-multi"
  2163. }).html([
  2164. "<ul class='select2-choices'>",
  2165. " <li class='select2-search-field'>",
  2166. " <label for='' class='select2-offscreen'></label>",
  2167. " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>",
  2168. " </li>",
  2169. "</ul>",
  2170. "<div class='select2-drop select2-drop-multi select2-display-none'>",
  2171. " <ul class='select2-results'>",
  2172. " </ul>",
  2173. "</div>"].join(""));
  2174. return container;
  2175. },
  2176. // multi
  2177. prepareOpts: function () {
  2178. var opts = this.parent.prepareOpts.apply(this, arguments),
  2179. self=this;
  2180. // TODO validate placeholder is a string if specified
  2181. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2182. // install the selection initializer
  2183. opts.initSelection = function (element, callback) {
  2184. var data = [];
  2185. element.find("option").filter(function() { return this.selected && !this.disabled }).each2(function (i, elm) {
  2186. data.push(self.optionToData(elm));
  2187. });
  2188. callback(data);
  2189. };
  2190. } else if ("data" in opts) {
  2191. // install default initSelection when applied to hidden input and data is local
  2192. opts.initSelection = opts.initSelection || function (element, callback) {
  2193. var ids = splitVal(element.val(), opts.separator, opts.transformVal);
  2194. //search in data by array of ids, storing matching items in a list
  2195. var matches = [];
  2196. opts.query({
  2197. matcher: function(term, text, el){
  2198. var is_match = $.grep(ids, function(id) {
  2199. return equal(id, opts.id(el));
  2200. }).length;
  2201. if (is_match) {
  2202. matches.push(el);
  2203. }
  2204. return is_match;
  2205. },
  2206. callback: !$.isFunction(callback) ? $.noop : function() {
  2207. // reorder matches based on the order they appear in the ids array because right now
  2208. // they are in the order in which they appear in data array
  2209. var ordered = [];
  2210. for (var i = 0; i < ids.length; i++) {
  2211. var id = ids[i];
  2212. for (var j = 0; j < matches.length; j++) {
  2213. var match = matches[j];
  2214. if (equal(id, opts.id(match))) {
  2215. ordered.push(match);
  2216. matches.splice(j, 1);
  2217. break;
  2218. }
  2219. }
  2220. }
  2221. callback(ordered);
  2222. }
  2223. });
  2224. };
  2225. }
  2226. return opts;
  2227. },
  2228. // multi
  2229. selectChoice: function (choice) {
  2230. var selected = this.container.find(".select2-search-choice-focus");
  2231. if (selected.length && choice && choice[0] == selected[0]) {
  2232. } else {
  2233. if (selected.length) {
  2234. this.opts.element.trigger("choice-deselected", selected);
  2235. }
  2236. selected.removeClass("select2-search-choice-focus");
  2237. if (choice && choice.length) {
  2238. this.close();
  2239. choice.addClass("select2-search-choice-focus");
  2240. this.opts.element.trigger("choice-selected", choice);
  2241. }
  2242. }
  2243. },
  2244. // multi
  2245. destroy: function() {
  2246. $("label[for='" + this.search.attr('id') + "']")
  2247. .attr('for', this.opts.element.attr("id"));
  2248. this.parent.destroy.apply(this, arguments);
  2249. cleanupJQueryElements.call(this,
  2250. "searchContainer",
  2251. "selection"
  2252. );
  2253. },
  2254. // multi
  2255. initContainer: function () {
  2256. var selector = ".select2-choices", selection;
  2257. this.searchContainer = this.container.find(".select2-search-field");
  2258. this.selection = selection = this.container.find(selector);
  2259. var _this = this;
  2260. this.selection.on("click", ".select2-container:not(.select2-container-disabled) .select2-search-choice:not(.select2-locked)", function (e) {
  2261. _this.search[0].focus();
  2262. _this.selectChoice($(this));
  2263. });
  2264. // rewrite labels from original element to focusser
  2265. this.search.attr("id", "s2id_autogen"+nextUid());
  2266. this.search.prev()
  2267. .text($("label[for='" + this.opts.element.attr("id") + "']").text())
  2268. .attr('for', this.search.attr('id'));
  2269. this.opts.element.focus(this.bind(function () { this.focus(); }));
  2270. this.search.on("input paste", this.bind(function() {
  2271. if (this.search.attr('placeholder') && this.search.val().length == 0) return;
  2272. if (!this.isInterfaceEnabled()) return;
  2273. if (!this.opened()) {
  2274. this.open();
  2275. }
  2276. }));
  2277. this.search.attr("tabindex", this.elementTabIndex);
  2278. this.keydowns = 0;
  2279. this.search.on("keydown", this.bind(function (e) {
  2280. if (!this.isInterfaceEnabled()) return;
  2281. ++this.keydowns;
  2282. var selected = selection.find(".select2-search-choice-focus");
  2283. var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
  2284. var next = selected.next(".select2-search-choice:not(.select2-locked)");
  2285. var pos = getCursorInfo(this.search);
  2286. if (selected.length &&
  2287. (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
  2288. var selectedChoice = selected;
  2289. if (e.which == KEY.LEFT && prev.length) {
  2290. selectedChoice = prev;
  2291. }
  2292. else if (e.which == KEY.RIGHT) {
  2293. selectedChoice = next.length ? next : null;
  2294. }
  2295. else if (e.which === KEY.BACKSPACE) {
  2296. if (this.unselect(selected.first())) {
  2297. this.search.width(10);
  2298. selectedChoice = prev.length ? prev : next;
  2299. }
  2300. } else if (e.which == KEY.DELETE) {
  2301. if (this.unselect(selected.first())) {
  2302. this.search.width(10);
  2303. selectedChoice = next.length ? next : null;
  2304. }
  2305. } else if (e.which == KEY.ENTER) {
  2306. selectedChoice = null;
  2307. }
  2308. this.selectChoice(selectedChoice);
  2309. killEvent(e);
  2310. if (!selectedChoice || !selectedChoice.length) {
  2311. this.open();
  2312. }
  2313. return;
  2314. } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
  2315. || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {
  2316. this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
  2317. killEvent(e);
  2318. return;
  2319. } else {
  2320. this.selectChoice(null);
  2321. }
  2322. if (this.opened()) {
  2323. switch (e.which) {
  2324. case KEY.UP:
  2325. case KEY.DOWN:
  2326. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  2327. killEvent(e);
  2328. return;
  2329. case KEY.ENTER:
  2330. this.selectHighlighted();
  2331. killEvent(e);
  2332. return;
  2333. case KEY.TAB:
  2334. this.selectHighlighted({noFocus:true});
  2335. this.close();
  2336. return;
  2337. case KEY.ESC:
  2338. this.cancel(e);
  2339. killEvent(e);
  2340. return;
  2341. }
  2342. }
  2343. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  2344. || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  2345. return;
  2346. }
  2347. if (e.which === KEY.ENTER) {
  2348. if (this.opts.openOnEnter === false) {
  2349. return;
  2350. } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
  2351. return;
  2352. }
  2353. }
  2354. this.open();
  2355. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  2356. // prevent the page from scrolling
  2357. killEvent(e);
  2358. }
  2359. if (e.which === KEY.ENTER) {
  2360. // prevent form from being submitted
  2361. killEvent(e);
  2362. }
  2363. }));
  2364. this.search.on("keyup", this.bind(function (e) {
  2365. this.keydowns = 0;
  2366. this.resizeSearch();
  2367. })
  2368. );
  2369. this.search.on("blur", this.bind(function(e) {
  2370. this.container.removeClass("select2-container-active");
  2371. this.search.removeClass("select2-focused");
  2372. this.selectChoice(null);
  2373. if (!this.opened()) this.clearSearch();
  2374. e.stopImmediatePropagation();
  2375. this.opts.element.trigger($.Event("select2-blur"));
  2376. }));
  2377. this.container.on("click", selector, this.bind(function (e) {
  2378. if (!this.isInterfaceEnabled()) return;
  2379. if ($(e.target).closest(".select2-search-choice").length > 0) {
  2380. // clicked inside a select2 search choice, do not open
  2381. return;
  2382. }
  2383. this.selectChoice(null);
  2384. this.clearPlaceholder();
  2385. if (!this.container.hasClass("select2-container-active")) {
  2386. this.opts.element.trigger($.Event("select2-focus"));
  2387. }
  2388. this.open();
  2389. this.focusSearch();
  2390. e.preventDefault();
  2391. }));
  2392. this.container.on("focus", selector, this.bind(function () {
  2393. if (!this.isInterfaceEnabled()) return;
  2394. if (!this.container.hasClass("select2-container-active")) {
  2395. this.opts.element.trigger($.Event("select2-focus"));
  2396. }
  2397. this.container.addClass("select2-container-active");
  2398. this.dropdown.addClass("select2-drop-active");
  2399. this.clearPlaceholder();
  2400. }));
  2401. this.initContainerWidth();
  2402. this.opts.element.hide();
  2403. // set the placeholder if necessary
  2404. this.clearSearch();
  2405. },
  2406. // multi
  2407. enableInterface: function() {
  2408. if (this.parent.enableInterface.apply(this, arguments)) {
  2409. this.search.prop("disabled", !this.isInterfaceEnabled());
  2410. }
  2411. },
  2412. // multi
  2413. initSelection: function () {
  2414. var data;
  2415. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  2416. this.updateSelection([]);
  2417. this.close();
  2418. // set the placeholder if necessary
  2419. this.clearSearch();
  2420. }
  2421. if (this.select || this.opts.element.val() !== "") {
  2422. var self = this;
  2423. this.opts.initSelection.call(null, this.opts.element, function(data){
  2424. if (data !== undefined && data !== null) {
  2425. self.updateSelection(data);
  2426. self.close();
  2427. // set the placeholder if necessary
  2428. self.clearSearch();
  2429. }
  2430. });
  2431. }
  2432. },
  2433. // multi
  2434. clearSearch: function () {
  2435. var placeholder = this.getPlaceholder(),
  2436. maxWidth = this.getMaxSearchWidth();
  2437. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  2438. this.search.val(placeholder).addClass("select2-default");
  2439. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  2440. // 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
  2441. this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
  2442. } else {
  2443. this.search.val("").width(10);
  2444. }
  2445. },
  2446. // multi
  2447. clearPlaceholder: function () {
  2448. if (this.search.hasClass("select2-default")) {
  2449. this.search.val("").removeClass("select2-default");
  2450. }
  2451. },
  2452. // multi
  2453. opening: function () {
  2454. this.clearPlaceholder(); // should be done before super so placeholder is not used to search
  2455. this.resizeSearch();
  2456. this.parent.opening.apply(this, arguments);
  2457. this.focusSearch();
  2458. // initializes search's value with nextSearchTerm (if defined by user)
  2459. // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
  2460. if(this.search.val() === "") {
  2461. if(this.nextSearchTerm != undefined){
  2462. this.search.val(this.nextSearchTerm);
  2463. this.search.select();
  2464. }
  2465. }
  2466. this.updateResults(true);
  2467. if (this.opts.shouldFocusInput(this)) {
  2468. this.search.focus();
  2469. }
  2470. this.opts.element.trigger($.Event("select2-open"));
  2471. },
  2472. // multi
  2473. close: function () {
  2474. if (!this.opened()) return;
  2475. this.parent.close.apply(this, arguments);
  2476. },
  2477. // multi
  2478. focus: function () {
  2479. this.close();
  2480. this.search.focus();
  2481. },
  2482. // multi
  2483. isFocused: function () {
  2484. return this.search.hasClass("select2-focused");
  2485. },
  2486. // multi
  2487. updateSelection: function (data) {
  2488. var ids = [], filtered = [], self = this;
  2489. // filter out duplicates
  2490. $(data).each(function () {
  2491. if (indexOf(self.id(this), ids) < 0) {
  2492. ids.push(self.id(this));
  2493. filtered.push(this);
  2494. }
  2495. });
  2496. data = filtered;
  2497. this.selection.find(".select2-search-choice").remove();
  2498. $(data).each(function () {
  2499. self.addSelectedChoice(this);
  2500. });
  2501. self.postprocessResults();
  2502. },
  2503. // multi
  2504. tokenize: function() {
  2505. var input = this.search.val();
  2506. input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
  2507. if (input != null && input != undefined) {
  2508. this.search.val(input);
  2509. if (input.length > 0) {
  2510. this.open();
  2511. }
  2512. }
  2513. },
  2514. // multi
  2515. onSelect: function (data, options) {
  2516. if (!this.triggerSelect(data) || data.text === "") { return; }
  2517. this.addSelectedChoice(data);
  2518. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  2519. // keep track of the search's value before it gets cleared
  2520. this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
  2521. this.clearSearch();
  2522. this.updateResults();
  2523. if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true);
  2524. if (this.opts.closeOnSelect) {
  2525. this.close();
  2526. this.search.width(10);
  2527. } else {
  2528. if (this.countSelectableResults()>0) {
  2529. this.search.width(10);
  2530. this.resizeSearch();
  2531. if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
  2532. // if we reached max selection size repaint the results so choices
  2533. // are replaced with the max selection reached message
  2534. this.updateResults(true);
  2535. } else {
  2536. // initializes search's value with nextSearchTerm and update search result
  2537. if(this.nextSearchTerm != undefined){
  2538. this.search.val(this.nextSearchTerm);
  2539. this.updateResults();
  2540. this.search.select();
  2541. }
  2542. }
  2543. this.positionDropdown();
  2544. } else {
  2545. // if nothing left to select close
  2546. this.close();
  2547. this.search.width(10);
  2548. }
  2549. }
  2550. // since its not possible to select an element that has already been
  2551. // added we do not need to check if this is a new element before firing change
  2552. this.triggerChange({ added: data });
  2553. if (!options || !options.noFocus)
  2554. this.focusSearch();
  2555. },
  2556. // multi
  2557. cancel: function () {
  2558. this.close();
  2559. this.focusSearch();
  2560. },
  2561. addSelectedChoice: function (data) {
  2562. var enableChoice = !data.locked,
  2563. enabledItem = $(
  2564. "<li class='select2-search-choice'>" +
  2565. " <div></div>" +
  2566. " <a href='#' class='select2-search-choice-close' tabindex='-1'></a>" +
  2567. "</li>"),
  2568. disabledItem = $(
  2569. "<li class='select2-search-choice select2-locked'>" +
  2570. "<div></div>" +
  2571. "</li>");
  2572. var choice = enableChoice ? enabledItem : disabledItem,
  2573. id = this.id(data),
  2574. val = this.getVal(),
  2575. formatted,
  2576. cssClass;
  2577. formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
  2578. if (formatted != undefined) {
  2579. choice.find("div").replaceWith($("<div></div>").html(formatted));
  2580. }
  2581. cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
  2582. if (cssClass != undefined) {
  2583. choice.addClass(cssClass);
  2584. }
  2585. if(enableChoice){
  2586. choice.find(".select2-search-choice-close")
  2587. .on("mousedown", killEvent)
  2588. .on("click dblclick", this.bind(function (e) {
  2589. if (!this.isInterfaceEnabled()) return;
  2590. this.unselect($(e.target));
  2591. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  2592. killEvent(e);
  2593. this.close();
  2594. this.focusSearch();
  2595. })).on("focus", this.bind(function () {
  2596. if (!this.isInterfaceEnabled()) return;
  2597. this.container.addClass("select2-container-active");
  2598. this.dropdown.addClass("select2-drop-active");
  2599. }));
  2600. }
  2601. choice.data("select2-data", data);
  2602. choice.insertBefore(this.searchContainer);
  2603. val.push(id);
  2604. this.setVal(val);
  2605. },
  2606. // multi
  2607. unselect: function (selected) {
  2608. var val = this.getVal(),
  2609. data,
  2610. index;
  2611. selected = selected.closest(".select2-search-choice");
  2612. if (selected.length === 0) {
  2613. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  2614. }
  2615. data = selected.data("select2-data");
  2616. if (!data) {
  2617. // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
  2618. // and invoked on an element already removed
  2619. return;
  2620. }
  2621. var evt = $.Event("select2-removing");
  2622. evt.val = this.id(data);
  2623. evt.choice = data;
  2624. this.opts.element.trigger(evt);
  2625. if (evt.isDefaultPrevented()) {
  2626. return false;
  2627. }
  2628. while((index = indexOf(this.id(data), val)) >= 0) {
  2629. val.splice(index, 1);
  2630. this.setVal(val);
  2631. if (this.select) this.postprocessResults();
  2632. }
  2633. selected.remove();
  2634. this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
  2635. this.triggerChange({ removed: data });
  2636. return true;
  2637. },
  2638. // multi
  2639. postprocessResults: function (data, initial, noHighlightUpdate) {
  2640. var val = this.getVal(),
  2641. choices = this.results.find(".select2-result"),
  2642. compound = this.results.find(".select2-result-with-children"),
  2643. self = this;
  2644. choices.each2(function (i, choice) {
  2645. var id = self.id(choice.data("select2-data"));
  2646. if (indexOf(id, val) >= 0) {
  2647. choice.addClass("select2-selected");
  2648. // mark all children of the selected parent as selected
  2649. choice.find(".select2-result-selectable").addClass("select2-selected");
  2650. }
  2651. });
  2652. compound.each2(function(i, choice) {
  2653. // hide an optgroup if it doesn't have any selectable children
  2654. if (!choice.is('.select2-result-selectable')
  2655. && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
  2656. choice.addClass("select2-selected");
  2657. }
  2658. });
  2659. if (this.highlight() == -1 && noHighlightUpdate !== false && this.opts.closeOnSelect === true){
  2660. self.highlight(0);
  2661. }
  2662. //If all results are chosen render formatNoMatches
  2663. if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
  2664. if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
  2665. if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
  2666. this.results.append("<li class='select2-no-results'>" + evaluate(self.opts.formatNoMatches, self.opts.element, self.search.val()) + "</li>");
  2667. }
  2668. }
  2669. }
  2670. },
  2671. // multi
  2672. getMaxSearchWidth: function() {
  2673. return this.selection.width() - getSideBorderPadding(this.search);
  2674. },
  2675. // multi
  2676. resizeSearch: function () {
  2677. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  2678. sideBorderPadding = getSideBorderPadding(this.search);
  2679. minimumWidth = measureTextWidth(this.search) + 10;
  2680. left = this.search.offset().left;
  2681. maxWidth = this.selection.width();
  2682. containerLeft = this.selection.offset().left;
  2683. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  2684. if (searchWidth < minimumWidth) {
  2685. searchWidth = maxWidth - sideBorderPadding;
  2686. }
  2687. if (searchWidth < 40) {
  2688. searchWidth = maxWidth - sideBorderPadding;
  2689. }
  2690. if (searchWidth <= 0) {
  2691. searchWidth = minimumWidth;
  2692. }
  2693. this.search.width(Math.floor(searchWidth));
  2694. },
  2695. // multi
  2696. getVal: function () {
  2697. var val;
  2698. if (this.select) {
  2699. val = this.select.val();
  2700. return val === null ? [] : val;
  2701. } else {
  2702. val = this.opts.element.val();
  2703. return splitVal(val, this.opts.separator, this.opts.transformVal);
  2704. }
  2705. },
  2706. // multi
  2707. setVal: function (val) {
  2708. var unique;
  2709. if (this.select) {
  2710. this.select.val(val);
  2711. } else {
  2712. unique = [];
  2713. // filter out duplicates
  2714. $(val).each(function () {
  2715. if (indexOf(this, unique) < 0) unique.push(this);
  2716. });
  2717. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  2718. }
  2719. },
  2720. // multi
  2721. buildChangeDetails: function (old, current) {
  2722. var current = current.slice(0),
  2723. old = old.slice(0);
  2724. // remove intersection from each array
  2725. for (var i = 0; i < current.length; i++) {
  2726. for (var j = 0; j < old.length; j++) {
  2727. if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
  2728. current.splice(i, 1);
  2729. if(i>0){
  2730. i--;
  2731. }
  2732. old.splice(j, 1);
  2733. j--;
  2734. }
  2735. }
  2736. }
  2737. return {added: current, removed: old};
  2738. },
  2739. // multi
  2740. val: function (val, triggerChange) {
  2741. var oldData, self=this;
  2742. if (arguments.length === 0) {
  2743. return this.getVal();
  2744. }
  2745. oldData=this.data();
  2746. if (!oldData.length) oldData=[];
  2747. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2748. if (!val && val !== 0) {
  2749. this.opts.element.val("");
  2750. this.updateSelection([]);
  2751. this.clearSearch();
  2752. if (triggerChange) {
  2753. this.triggerChange({added: this.data(), removed: oldData});
  2754. }
  2755. return;
  2756. }
  2757. // val is a list of ids
  2758. this.setVal(val);
  2759. if (this.select) {
  2760. this.opts.initSelection(this.select, this.bind(this.updateSelection));
  2761. if (triggerChange) {
  2762. this.triggerChange(this.buildChangeDetails(oldData, this.data()));
  2763. }
  2764. } else {
  2765. if (this.opts.initSelection === undefined) {
  2766. throw new Error("val() cannot be called if initSelection() is not defined");
  2767. }
  2768. this.opts.initSelection(this.opts.element, function(data){
  2769. var ids=$.map(data, self.id);
  2770. self.setVal(ids);
  2771. self.updateSelection(data);
  2772. self.clearSearch();
  2773. if (triggerChange) {
  2774. self.triggerChange(self.buildChangeDetails(oldData, self.data()));
  2775. }
  2776. });
  2777. }
  2778. this.clearSearch();
  2779. },
  2780. // multi
  2781. onSortStart: function() {
  2782. if (this.select) {
  2783. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  2784. }
  2785. // collapse search field into 0 width so its container can be collapsed as well
  2786. this.search.width(0);
  2787. // hide the container
  2788. this.searchContainer.hide();
  2789. },
  2790. // multi
  2791. onSortEnd:function() {
  2792. var val=[], self=this;
  2793. // show search and move it to the end of the list
  2794. this.searchContainer.show();
  2795. // make sure the search container is the last item in the list
  2796. this.searchContainer.appendTo(this.searchContainer.parent());
  2797. // since we collapsed the width in dragStarted, we resize it here
  2798. this.resizeSearch();
  2799. // update selection
  2800. this.selection.find(".select2-search-choice").each(function() {
  2801. val.push(self.opts.id($(this).data("select2-data")));
  2802. });
  2803. this.setVal(val);
  2804. this.triggerChange();
  2805. },
  2806. // multi
  2807. data: function(values, triggerChange) {
  2808. var self=this, ids, old;
  2809. if (arguments.length === 0) {
  2810. return this.selection
  2811. .children(".select2-search-choice")
  2812. .map(function() { return $(this).data("select2-data"); })
  2813. .get();
  2814. } else {
  2815. old = this.data();
  2816. if (!values) { values = []; }
  2817. ids = $.map(values, function(e) { return self.opts.id(e); });
  2818. this.setVal(ids);
  2819. this.updateSelection(values);
  2820. this.clearSearch();
  2821. if (triggerChange) {
  2822. this.triggerChange(this.buildChangeDetails(old, this.data()));
  2823. }
  2824. }
  2825. }
  2826. });
  2827. $.fn.select2 = function () {
  2828. var args = Array.prototype.slice.call(arguments, 0),
  2829. opts,
  2830. select2,
  2831. method, value, multiple,
  2832. allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"],
  2833. valueMethods = ["opened", "isFocused", "container", "dropdown"],
  2834. propertyMethods = ["val", "data"],
  2835. methodsMap = { search: "externalSearch" };
  2836. this.each(function () {
  2837. if (args.length === 0 || typeof(args[0]) === "object") {
  2838. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  2839. opts.element = $(this);
  2840. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2841. multiple = opts.element.prop("multiple");
  2842. } else {
  2843. multiple = opts.multiple || false;
  2844. if ("tags" in opts) {opts.multiple = multiple = true;}
  2845. }
  2846. select2 = multiple ? new window.Select2["class"].multi() : new window.Select2["class"].single();
  2847. select2.init(opts);
  2848. } else if (typeof(args[0]) === "string") {
  2849. if (indexOf(args[0], allowedMethods) < 0) {
  2850. throw "Unknown method: " + args[0];
  2851. }
  2852. value = undefined;
  2853. select2 = $(this).data("select2");
  2854. if (select2 === undefined) return;
  2855. method=args[0];
  2856. if (method === "container") {
  2857. value = select2.container;
  2858. } else if (method === "dropdown") {
  2859. value = select2.dropdown;
  2860. } else {
  2861. if (methodsMap[method]) method = methodsMap[method];
  2862. value = select2[method].apply(select2, args.slice(1));
  2863. }
  2864. if (indexOf(args[0], valueMethods) >= 0
  2865. || (indexOf(args[0], propertyMethods) >= 0 && args.length == 1)) {
  2866. return false; // abort the iteration, ready to return first matched value
  2867. }
  2868. } else {
  2869. throw "Invalid arguments to select2 plugin: " + args;
  2870. }
  2871. });
  2872. return (value === undefined) ? this : value;
  2873. };
  2874. // plugin defaults, accessible to users
  2875. $.fn.select2.defaults = {
  2876. width: "copy",
  2877. loadMorePadding: 0,
  2878. closeOnSelect: true,
  2879. openOnEnter: true,
  2880. containerCss: {},
  2881. dropdownCss: {},
  2882. containerCssClass: "",
  2883. dropdownCssClass: "",
  2884. formatResult: function(result, container, query, escapeMarkup) {
  2885. var markup=[];
  2886. markMatch(this.text(result), query.term, markup, escapeMarkup);
  2887. return markup.join("");
  2888. },
  2889. transformVal: function(val) {
  2890. return $.trim(val);
  2891. },
  2892. formatSelection: function (data, container, escapeMarkup) {
  2893. return data ? escapeMarkup(this.text(data)) : undefined;
  2894. },
  2895. sortResults: function (results, container, query) {
  2896. return results;
  2897. },
  2898. formatResultCssClass: function(data) {return data.css;},
  2899. formatSelectionCssClass: function(data, container) {return undefined;},
  2900. minimumResultsForSearch: 0,
  2901. minimumInputLength: 0,
  2902. maximumInputLength: null,
  2903. maximumSelectionSize: 0,
  2904. id: function (e) { return e == undefined ? null : e.id; },
  2905. text: function (e) {
  2906. if (e && this.data && this.data.text) {
  2907. if ($.isFunction(this.data.text)) {
  2908. return this.data.text(e);
  2909. } else {
  2910. return e[this.data.text];
  2911. }
  2912. } else {
  2913. return e.text;
  2914. }
  2915. },
  2916. matcher: function(term, text) {
  2917. return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
  2918. },
  2919. separator: ",",
  2920. tokenSeparators: [],
  2921. tokenizer: defaultTokenizer,
  2922. escapeMarkup: defaultEscapeMarkup,
  2923. blurOnChange: false,
  2924. selectOnBlur: false,
  2925. adaptContainerCssClass: function(c) { return c; },
  2926. adaptDropdownCssClass: function(c) { return null; },
  2927. nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; },
  2928. searchInputPlaceholder: '',
  2929. createSearchChoicePosition: 'top',
  2930. shouldFocusInput: function (instance) {
  2931. // Attempt to detect touch devices
  2932. var supportsTouchEvents = (('ontouchstart' in window) ||
  2933. (navigator.msMaxTouchPoints > 0));
  2934. // Only devices which support touch events should be special cased
  2935. if (!supportsTouchEvents) {
  2936. return true;
  2937. }
  2938. // Never focus the input if search is disabled
  2939. if (instance.opts.minimumResultsForSearch < 0) {
  2940. return false;
  2941. }
  2942. return true;
  2943. }
  2944. };
  2945. $.fn.select2.locales = [];
  2946. $.fn.select2.locales['en'] = {
  2947. formatMatches: function (matches) { if (matches === 1) { return "One result is available, press enter to select it."; } return matches + " results are available, use up and down arrow keys to navigate."; },
  2948. formatNoMatches: function () { return "No matches found"; },
  2949. formatAjaxError: function (jqXHR, textStatus, errorThrown) { return "Loading failed"; },
  2950. formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1 ? "" : "s"); },
  2951. formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1 ? "" : "s"); },
  2952. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
  2953. formatLoadMore: function (pageNumber) { return "Loading more results…"; },
  2954. formatSearching: function () { return "Searching…"; }
  2955. };
  2956. $.extend($.fn.select2.defaults, $.fn.select2.locales['en']);
  2957. $.fn.select2.ajaxDefaults = {
  2958. transport: $.ajax,
  2959. params: {
  2960. type: "GET",
  2961. cache: false,
  2962. dataType: "json"
  2963. }
  2964. };
  2965. // exports
  2966. window.Select2 = {
  2967. query: {
  2968. ajax: ajax,
  2969. local: local,
  2970. tags: tags
  2971. }, util: {
  2972. debounce: debounce,
  2973. markMatch: markMatch,
  2974. escapeMarkup: defaultEscapeMarkup,
  2975. stripDiacritics: stripDiacritics
  2976. }, "class": {
  2977. "abstract": AbstractSelect2,
  2978. "single": SingleSelect2,
  2979. "multi": MultiSelect2
  2980. }
  2981. };
  2982. }(jQuery));