select2.js 129 KB

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