select2.js 129 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173
  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. handler = null,
  364. quietMillis = options.quietMillis || 100,
  365. ajaxUrl = options.url,
  366. self = this;
  367. return function (query) {
  368. window.clearTimeout(timeout);
  369. timeout = window.setTimeout(function () {
  370. var data = options.data, // ajax data function
  371. url = ajaxUrl, // ajax url string or function
  372. transport = options.transport || $.fn.select2.ajaxDefaults.transport,
  373. // deprecated - to be removed in 4.0 - use params instead
  374. deprecated = {
  375. type: options.type || 'GET', // set type of request (GET or POST)
  376. cache: options.cache || false,
  377. jsonpCallback: options.jsonpCallback||undefined,
  378. dataType: options.dataType||"json"
  379. },
  380. params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
  381. data = data ? data.call(self, query.term, query.page, query.context) : null;
  382. url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
  383. if (handler) { handler.abort(); }
  384. if (options.params) {
  385. if ($.isFunction(options.params)) {
  386. $.extend(params, options.params.call(self));
  387. } else {
  388. $.extend(params, options.params);
  389. }
  390. }
  391. $.extend(params, {
  392. url: url,
  393. dataType: options.dataType,
  394. data: data,
  395. success: function (data) {
  396. // TODO - replace query.page with query so users have access to term, page, etc.
  397. var results = options.results(data, query.page);
  398. query.callback(results);
  399. }
  400. });
  401. handler = transport.call(self, params);
  402. }, quietMillis);
  403. };
  404. }
  405. /**
  406. * Produces a query function that works with a local array
  407. *
  408. * @param options object containing configuration parameters. The options parameter can either be an array or an
  409. * object.
  410. *
  411. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  412. *
  413. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  414. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  415. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  416. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  417. * the text.
  418. */
  419. function local(options) {
  420. var data = options, // data elements
  421. dataText,
  422. tmp,
  423. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  424. if ($.isArray(data)) {
  425. tmp = data;
  426. data = { results: tmp };
  427. }
  428. if ($.isFunction(data) === false) {
  429. tmp = data;
  430. data = function() { return tmp; };
  431. }
  432. var dataItem = data();
  433. if (dataItem.text) {
  434. text = dataItem.text;
  435. // if text is not a function we assume it to be a key name
  436. if (!$.isFunction(text)) {
  437. 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
  438. text = function (item) { return item[dataText]; };
  439. }
  440. }
  441. return function (query) {
  442. var t = query.term, filtered = { results: [] }, process;
  443. if (t === "") {
  444. query.callback(data());
  445. return;
  446. }
  447. process = function(datum, collection) {
  448. var group, attr;
  449. datum = datum[0];
  450. if (datum.children) {
  451. group = {};
  452. for (attr in datum) {
  453. if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
  454. }
  455. group.children=[];
  456. $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
  457. if (group.children.length || query.matcher(t, text(group), datum)) {
  458. collection.push(group);
  459. }
  460. } else {
  461. if (query.matcher(t, text(datum), datum)) {
  462. collection.push(datum);
  463. }
  464. }
  465. };
  466. $(data().results).each2(function(i, datum) { process(datum, filtered.results); });
  467. query.callback(filtered);
  468. };
  469. }
  470. // TODO javadoc
  471. function tags(data) {
  472. var isFunc = $.isFunction(data);
  473. return function (query) {
  474. var t = query.term, filtered = {results: []};
  475. $(isFunc ? data() : data).each(function () {
  476. var isObject = this.text !== undefined,
  477. text = isObject ? this.text : this;
  478. if (t === "" || query.matcher(t, text)) {
  479. filtered.results.push(isObject ? this : {id: this, text: this});
  480. }
  481. });
  482. query.callback(filtered);
  483. };
  484. }
  485. /**
  486. * Checks if the formatter function should be used.
  487. *
  488. * Throws an error if it is not a function. Returns true if it should be used,
  489. * false if no formatting should be performed.
  490. *
  491. * @param formatter
  492. */
  493. function checkFormatter(formatter, formatterName) {
  494. if ($.isFunction(formatter)) return true;
  495. if (!formatter) return false;
  496. throw new Error(formatterName +" must be a function or a falsy value");
  497. }
  498. function evaluate(val) {
  499. return $.isFunction(val) ? val() : val;
  500. }
  501. function countResults(results) {
  502. var count = 0;
  503. $.each(results, function(i, item) {
  504. if (item.children) {
  505. count += countResults(item.children);
  506. } else {
  507. count++;
  508. }
  509. });
  510. return count;
  511. }
  512. /**
  513. * Default tokenizer. This function uses breaks the input on substring match of any string from the
  514. * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
  515. * two options have to be defined in order for the tokenizer to work.
  516. *
  517. * @param input text user has typed so far or pasted into the search field
  518. * @param selection currently selected choices
  519. * @param selectCallback function(choice) callback tho add the choice to selection
  520. * @param opts select2's opts
  521. * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
  522. */
  523. function defaultTokenizer(input, selection, selectCallback, opts) {
  524. var original = input, // store the original so we can compare and know if we need to tell the search to update its text
  525. dupe = false, // check for whether a token we extracted represents a duplicate selected choice
  526. token, // token
  527. index, // position at which the separator was found
  528. i, l, // looping variables
  529. separator; // the matched separator
  530. if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
  531. while (true) {
  532. index = -1;
  533. for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
  534. separator = opts.tokenSeparators[i];
  535. index = input.indexOf(separator);
  536. if (index >= 0) break;
  537. }
  538. if (index < 0) break; // did not find any token separator in the input string, bail
  539. token = input.substring(0, index);
  540. input = input.substring(index + separator.length);
  541. if (token.length > 0) {
  542. token = opts.createSearchChoice.call(this, token, selection);
  543. if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
  544. dupe = false;
  545. for (i = 0, l = selection.length; i < l; i++) {
  546. if (equal(opts.id(token), opts.id(selection[i]))) {
  547. dupe = true; break;
  548. }
  549. }
  550. if (!dupe) selectCallback(token);
  551. }
  552. }
  553. }
  554. if (original!==input) return input;
  555. }
  556. /**
  557. * Creates a new class
  558. *
  559. * @param superClass
  560. * @param methods
  561. */
  562. function clazz(SuperClass, methods) {
  563. var constructor = function () {};
  564. constructor.prototype = new SuperClass;
  565. constructor.prototype.constructor = constructor;
  566. constructor.prototype.parent = SuperClass.prototype;
  567. constructor.prototype = $.extend(constructor.prototype, methods);
  568. return constructor;
  569. }
  570. AbstractSelect2 = clazz(Object, {
  571. // abstract
  572. bind: function (func) {
  573. var self = this;
  574. return function () {
  575. func.apply(self, arguments);
  576. };
  577. },
  578. // abstract
  579. init: function (opts) {
  580. var results, search, resultsSelector = ".select2-results", disabled, readonly;
  581. // prepare options
  582. this.opts = opts = this.prepareOpts(opts);
  583. this.id=opts.id;
  584. // destroy if called on an existing component
  585. if (opts.element.data("select2") !== undefined &&
  586. opts.element.data("select2") !== null) {
  587. opts.element.data("select2").destroy();
  588. }
  589. this.container = this.createContainer();
  590. this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
  591. this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
  592. this.container.attr("id", this.containerId);
  593. // cache the body so future lookups are cheap
  594. this.body = thunk(function() { return opts.element.closest("body"); });
  595. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  596. this.container.attr("style", opts.element.attr("style"));
  597. this.container.css(evaluate(opts.containerCss));
  598. this.container.addClass(evaluate(opts.containerCssClass));
  599. this.elementTabIndex = this.opts.element.attr("tabindex");
  600. // swap container for the element
  601. this.opts.element
  602. .data("select2", this)
  603. .attr("tabindex", "-1")
  604. .before(this.container);
  605. this.container.data("select2", this);
  606. this.dropdown = this.container.find(".select2-drop");
  607. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  608. this.dropdown.data("select2", this);
  609. this.results = results = this.container.find(resultsSelector);
  610. this.search = search = this.container.find("input.select2-input");
  611. this.queryCount = 0;
  612. this.resultsPage = 0;
  613. this.context = null;
  614. // initialize the container
  615. this.initContainer();
  616. installFilteredMouseMove(this.results);
  617. this.dropdown.on("mousemove-filtered touchstart touchmove touchend", resultsSelector, this.bind(this.highlightUnderEvent));
  618. installDebouncedScroll(80, this.results);
  619. this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));
  620. // do not propagate change event from the search field out of the component
  621. $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
  622. $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});
  623. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  624. if ($.fn.mousewheel) {
  625. results.mousewheel(function (e, delta, deltaX, deltaY) {
  626. var top = results.scrollTop(), height;
  627. if (deltaY > 0 && top - deltaY <= 0) {
  628. results.scrollTop(0);
  629. killEvent(e);
  630. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  631. results.scrollTop(results.get(0).scrollHeight - results.height());
  632. killEvent(e);
  633. }
  634. });
  635. }
  636. installKeyUpChangeEvent(search);
  637. search.on("keyup-change input paste", this.bind(this.updateResults));
  638. search.on("focus", function () { search.addClass("select2-focused"); });
  639. search.on("blur", function () { search.removeClass("select2-focused");});
  640. this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
  641. if ($(e.target).closest(".select2-result-selectable").length > 0) {
  642. this.highlightUnderEvent(e);
  643. this.selectHighlighted(e);
  644. }
  645. }));
  646. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  647. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  648. // dom it will trigger the popup close, which is not what we want
  649. this.dropdown.on("click mouseup mousedown", function (e) { e.stopPropagation(); });
  650. if ($.isFunction(this.opts.initSelection)) {
  651. // initialize selection based on the current value of the source element
  652. this.initSelection();
  653. // if the user has provided a function that can set selection based on the value of the source element
  654. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  655. this.monitorSource();
  656. }
  657. if (opts.maximumInputLength !== null) {
  658. this.search.attr("maxlength", opts.maximumInputLength);
  659. }
  660. var disabled = opts.element.prop("disabled");
  661. if (disabled === undefined) disabled = false;
  662. this.enable(!disabled);
  663. var readonly = opts.element.prop("readonly");
  664. if (readonly === undefined) readonly = false;
  665. this.readonly(readonly);
  666. // Calculate size of scrollbar
  667. scrollBarDimensions = scrollBarDimensions || measureScrollbar();
  668. this.autofocus = opts.element.prop("autofocus");
  669. opts.element.prop("autofocus", false);
  670. if (this.autofocus) this.focus();
  671. },
  672. // abstract
  673. destroy: function () {
  674. var element=this.opts.element, select2 = element.data("select2");
  675. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  676. if (select2 !== undefined) {
  677. select2.container.remove();
  678. select2.dropdown.remove();
  679. element
  680. .removeClass("select2-offscreen")
  681. .removeData("select2")
  682. .off(".select2")
  683. .prop("autofocus", this.autofocus || false);
  684. if (this.elementTabIndex) {
  685. element.attr({tabindex: this.elementTabIndex});
  686. } else {
  687. element.removeAttr("tabindex");
  688. }
  689. element.show();
  690. }
  691. },
  692. // abstract
  693. optionToData: function(element) {
  694. if (element.is("option")) {
  695. return {
  696. id:element.prop("value"),
  697. text:element.text(),
  698. element: element.get(),
  699. css: element.attr("class"),
  700. disabled: element.prop("disabled"),
  701. locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
  702. };
  703. } else if (element.is("optgroup")) {
  704. return {
  705. text:element.attr("label"),
  706. children:[],
  707. element: element.get(),
  708. css: element.attr("class")
  709. };
  710. }
  711. },
  712. // abstract
  713. prepareOpts: function (opts) {
  714. var element, select, idKey, ajaxUrl, self = this;
  715. element = opts.element;
  716. if (element.get(0).tagName.toLowerCase() === "select") {
  717. this.select = select = opts.element;
  718. }
  719. if (select) {
  720. // these options are not allowed when attached to a select because they are picked up off the element itself
  721. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  722. if (this in opts) {
  723. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  724. }
  725. });
  726. }
  727. opts = $.extend({}, {
  728. populateResults: function(container, results, query) {
  729. var populate, data, result, children, id=this.opts.id;
  730. populate=function(results, container, depth) {
  731. var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
  732. results = opts.sortResults(results, container, query);
  733. for (i = 0, l = results.length; i < l; i = i + 1) {
  734. result=results[i];
  735. disabled = (result.disabled === true);
  736. selectable = (!disabled) && (id(result) !== undefined);
  737. compound=result.children && result.children.length > 0;
  738. node=$("<li></li>");
  739. node.addClass("select2-results-dept-"+depth);
  740. node.addClass("select2-result");
  741. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  742. if (disabled) { node.addClass("select2-disabled"); }
  743. if (compound) { node.addClass("select2-result-with-children"); }
  744. node.addClass(self.opts.formatResultCssClass(result));
  745. label=$(document.createElement("div"));
  746. label.addClass("select2-result-label");
  747. formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
  748. if (formatted!==undefined) {
  749. label.html(formatted);
  750. }
  751. node.append(label);
  752. if (compound) {
  753. innerContainer=$("<ul></ul>");
  754. innerContainer.addClass("select2-result-sub");
  755. populate(result.children, innerContainer, depth+1);
  756. node.append(innerContainer);
  757. }
  758. node.data("select2-data", result);
  759. container.append(node);
  760. }
  761. };
  762. populate(results, container, 0);
  763. }
  764. }, $.fn.select2.defaults, opts);
  765. if (typeof(opts.id) !== "function") {
  766. idKey = opts.id;
  767. opts.id = function (e) { return e[idKey]; };
  768. }
  769. if ($.isArray(opts.element.data("select2Tags"))) {
  770. if ("tags" in opts) {
  771. throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
  772. }
  773. opts.tags=opts.element.data("select2Tags");
  774. }
  775. if (select) {
  776. opts.query = this.bind(function (query) {
  777. var data = { results: [], more: false },
  778. term = query.term,
  779. children, placeholderOption, process;
  780. process=function(element, collection) {
  781. var group;
  782. if (element.is("option")) {
  783. if (query.matcher(term, element.text(), element)) {
  784. collection.push(self.optionToData(element));
  785. }
  786. } else if (element.is("optgroup")) {
  787. group=self.optionToData(element);
  788. element.children().each2(function(i, elm) { process(elm, group.children); });
  789. if (group.children.length>0) {
  790. collection.push(group);
  791. }
  792. }
  793. };
  794. children=element.children();
  795. // ignore the placeholder option if there is one
  796. if (this.getPlaceholder() !== undefined && children.length > 0) {
  797. placeholderOption = this.getPlaceholderOption();
  798. if (placeholderOption) {
  799. children=children.not(placeholderOption);
  800. }
  801. }
  802. children.each2(function(i, elm) { process(elm, data.results); });
  803. query.callback(data);
  804. });
  805. // this is needed because inside val() we construct choices from options and there id is hardcoded
  806. opts.id=function(e) { return e.id; };
  807. opts.formatResultCssClass = function(data) { return data.css; };
  808. } else {
  809. if (!("query" in opts)) {
  810. if ("ajax" in opts) {
  811. ajaxUrl = opts.element.data("ajax-url");
  812. if (ajaxUrl && ajaxUrl.length > 0) {
  813. opts.ajax.url = ajaxUrl;
  814. }
  815. opts.query = ajax.call(opts.element, opts.ajax);
  816. } else if ("data" in opts) {
  817. opts.query = local(opts.data);
  818. } else if ("tags" in opts) {
  819. opts.query = tags(opts.tags);
  820. if (opts.createSearchChoice === undefined) {
  821. opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; };
  822. }
  823. if (opts.initSelection === undefined) {
  824. opts.initSelection = function (element, callback) {
  825. var data = [];
  826. $(splitVal(element.val(), opts.separator)).each(function () {
  827. var id = this, text = this, tags=opts.tags;
  828. if ($.isFunction(tags)) tags=tags();
  829. $(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } });
  830. data.push({id: id, text: text});
  831. });
  832. callback(data);
  833. };
  834. }
  835. }
  836. }
  837. }
  838. if (typeof(opts.query) !== "function") {
  839. throw "query function not defined for Select2 " + opts.element.attr("id");
  840. }
  841. return opts;
  842. },
  843. /**
  844. * Monitor the original element for changes and update select2 accordingly
  845. */
  846. // abstract
  847. monitorSource: function () {
  848. var el = this.opts.element, sync;
  849. el.on("change.select2", this.bind(function (e) {
  850. if (this.opts.element.data("select2-change-triggered") !== true) {
  851. this.initSelection();
  852. }
  853. }));
  854. sync = this.bind(function () {
  855. var enabled, readonly, self = this;
  856. // sync enabled state
  857. var disabled = el.prop("disabled");
  858. if (disabled === undefined) disabled = false;
  859. this.enable(!disabled);
  860. var readonly = el.prop("readonly");
  861. if (readonly === undefined) readonly = false;
  862. this.readonly(readonly);
  863. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  864. this.container.addClass(evaluate(this.opts.containerCssClass));
  865. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  866. this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
  867. });
  868. // mozilla and IE
  869. el.on("propertychange.select2 DOMAttrModified.select2", sync);
  870. // hold onto a reference of the callback to work around a chromium bug
  871. if (this.mutationCallback === undefined) {
  872. this.mutationCallback = function (mutations) {
  873. mutations.forEach(sync);
  874. }
  875. }
  876. // safari and chrome
  877. if (typeof WebKitMutationObserver !== "undefined") {
  878. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  879. this.propertyObserver = new WebKitMutationObserver(this.mutationCallback);
  880. this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
  881. }
  882. },
  883. // abstract
  884. triggerSelect: function(data) {
  885. var evt = $.Event("select2-selecting", { val: this.id(data), object: data });
  886. this.opts.element.trigger(evt);
  887. return !evt.isDefaultPrevented();
  888. },
  889. /**
  890. * Triggers the change event on the source element
  891. */
  892. // abstract
  893. triggerChange: function (details) {
  894. details = details || {};
  895. details= $.extend({}, details, { type: "change", val: this.val() });
  896. // prevents recursive triggering
  897. this.opts.element.data("select2-change-triggered", true);
  898. this.opts.element.trigger(details);
  899. this.opts.element.data("select2-change-triggered", false);
  900. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  901. // so here we trigger the click event manually
  902. this.opts.element.click();
  903. // ValidationEngine ignorea the change event and listens instead to blur
  904. // so here we trigger the blur event manually if so desired
  905. if (this.opts.blurOnChange)
  906. this.opts.element.blur();
  907. },
  908. //abstract
  909. isInterfaceEnabled: function()
  910. {
  911. return this.enabledInterface === true;
  912. },
  913. // abstract
  914. enableInterface: function() {
  915. var enabled = this._enabled && !this._readonly,
  916. disabled = !enabled;
  917. if (enabled === this.enabledInterface) return false;
  918. this.container.toggleClass("select2-container-disabled", disabled);
  919. this.close();
  920. this.enabledInterface = enabled;
  921. return true;
  922. },
  923. // abstract
  924. enable: function(enabled) {
  925. if (enabled === undefined) enabled = true;
  926. if (this._enabled === enabled) return;
  927. this._enabled = enabled;
  928. this.opts.element.prop("disabled", !enabled);
  929. this.enableInterface();
  930. },
  931. // abstract
  932. disable: function() {
  933. this.enable(false);
  934. },
  935. // abstract
  936. readonly: function(enabled) {
  937. if (enabled === undefined) enabled = false;
  938. if (this._readonly === enabled) return false;
  939. this._readonly = enabled;
  940. this.opts.element.prop("readonly", enabled);
  941. this.enableInterface();
  942. return true;
  943. },
  944. // abstract
  945. opened: function () {
  946. return this.container.hasClass("select2-dropdown-open");
  947. },
  948. // abstract
  949. positionDropdown: function() {
  950. var $dropdown = this.dropdown,
  951. offset = this.container.offset(),
  952. height = this.container.outerHeight(false),
  953. width = this.container.outerWidth(false),
  954. dropHeight = $dropdown.outerHeight(false),
  955. viewPortRight = $(window).scrollLeft() + $(window).width(),
  956. viewportBottom = $(window).scrollTop() + $(window).height(),
  957. dropTop = offset.top + height,
  958. dropLeft = offset.left,
  959. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  960. enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
  961. dropWidth = $dropdown.outerWidth(false),
  962. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
  963. aboveNow = $dropdown.hasClass("select2-drop-above"),
  964. bodyOffset,
  965. above,
  966. css,
  967. resultsListNode;
  968. if (this.opts.dropdownAutoWidth) {
  969. resultsListNode = $('.select2-results', $dropdown)[0];
  970. $dropdown.addClass('select2-drop-auto-width');
  971. $dropdown.css('width', '');
  972. // Add scrollbar width to dropdown if vertical scrollbar is present
  973. dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
  974. dropWidth > width ? width = dropWidth : dropWidth = width;
  975. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
  976. }
  977. else {
  978. this.container.removeClass('select2-drop-auto-width');
  979. }
  980. //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  981. //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  982. // fix positioning when body has an offset and is not position: static
  983. if (this.body().css('position') !== 'static') {
  984. bodyOffset = this.body().offset();
  985. dropTop -= bodyOffset.top;
  986. dropLeft -= bodyOffset.left;
  987. }
  988. // always prefer the current above/below alignment, unless there is not enough room
  989. if (aboveNow) {
  990. above = true;
  991. if (!enoughRoomAbove && enoughRoomBelow) above = false;
  992. } else {
  993. above = false;
  994. if (!enoughRoomBelow && enoughRoomAbove) above = true;
  995. }
  996. if (!enoughRoomOnRight) {
  997. dropLeft = offset.left + width - dropWidth;
  998. }
  999. if (above) {
  1000. dropTop = offset.top - dropHeight;
  1001. this.container.addClass("select2-drop-above");
  1002. $dropdown.addClass("select2-drop-above");
  1003. }
  1004. else {
  1005. this.container.removeClass("select2-drop-above");
  1006. $dropdown.removeClass("select2-drop-above");
  1007. }
  1008. css = $.extend({
  1009. top: dropTop,
  1010. left: dropLeft,
  1011. width: width
  1012. }, evaluate(this.opts.dropdownCss));
  1013. $dropdown.css(css);
  1014. },
  1015. // abstract
  1016. shouldOpen: function() {
  1017. var event;
  1018. if (this.opened()) return false;
  1019. if (this._enabled === false || this._readonly === true) return false;
  1020. event = $.Event("select2-opening");
  1021. this.opts.element.trigger(event);
  1022. return !event.isDefaultPrevented();
  1023. },
  1024. // abstract
  1025. clearDropdownAlignmentPreference: function() {
  1026. // clear the classes used to figure out the preference of where the dropdown should be opened
  1027. this.container.removeClass("select2-drop-above");
  1028. this.dropdown.removeClass("select2-drop-above");
  1029. },
  1030. /**
  1031. * Opens the dropdown
  1032. *
  1033. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  1034. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  1035. */
  1036. // abstract
  1037. open: function () {
  1038. if (!this.shouldOpen()) return false;
  1039. this.opening();
  1040. return true;
  1041. },
  1042. /**
  1043. * Performs the opening of the dropdown
  1044. */
  1045. // abstract
  1046. opening: function() {
  1047. var cid = this.containerId,
  1048. scroll = "scroll." + cid,
  1049. resize = "resize."+cid,
  1050. orient = "orientationchange."+cid,
  1051. mask, maskCss;
  1052. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  1053. this.clearDropdownAlignmentPreference();
  1054. if(this.dropdown[0] !== this.body().children().last()[0]) {
  1055. this.dropdown.detach().appendTo(this.body());
  1056. }
  1057. // create the dropdown mask if doesnt already exist
  1058. mask = $("#select2-drop-mask");
  1059. if (mask.length == 0) {
  1060. mask = $(document.createElement("div"));
  1061. mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
  1062. mask.hide();
  1063. mask.appendTo(this.body());
  1064. mask.on("mousedown touchstart click", function (e) {
  1065. var dropdown = $("#select2-drop"), self;
  1066. if (dropdown.length > 0) {
  1067. self=dropdown.data("select2");
  1068. if (self.opts.selectOnBlur) {
  1069. self.selectHighlighted({noFocus: true});
  1070. }
  1071. self.close();
  1072. e.preventDefault();
  1073. e.stopPropagation();
  1074. }
  1075. });
  1076. }
  1077. // ensure the mask is always right before the dropdown
  1078. if (this.dropdown.prev()[0] !== mask[0]) {
  1079. this.dropdown.before(mask);
  1080. }
  1081. // move the global id to the correct dropdown
  1082. $("#select2-drop").removeAttr("id");
  1083. this.dropdown.attr("id", "select2-drop");
  1084. // show the elements
  1085. maskCss=_makeMaskCss();
  1086. mask.css(maskCss).show();
  1087. this.dropdown.show();
  1088. this.positionDropdown();
  1089. this.dropdown.addClass("select2-drop-active");
  1090. // attach listeners to events that can change the position of the container and thus require
  1091. // the position of the dropdown to be updated as well so it does not come unglued from the container
  1092. var that = this;
  1093. this.container.parents().add(window).each(function () {
  1094. $(this).on(resize+" "+scroll+" "+orient, function (e) {
  1095. var maskCss=_makeMaskCss();
  1096. $("#select2-drop-mask").css(maskCss);
  1097. that.positionDropdown();
  1098. });
  1099. });
  1100. function _makeMaskCss() {
  1101. return {
  1102. width : Math.max(document.documentElement.scrollWidth, $(window).width()),
  1103. height : Math.max(document.documentElement.scrollHeight, $(window).height())
  1104. }
  1105. }
  1106. },
  1107. // abstract
  1108. close: function () {
  1109. if (!this.opened()) return;
  1110. var cid = this.containerId,
  1111. scroll = "scroll." + cid,
  1112. resize = "resize."+cid,
  1113. orient = "orientationchange."+cid;
  1114. // unbind event listeners
  1115. this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });
  1116. this.clearDropdownAlignmentPreference();
  1117. $("#select2-drop-mask").hide();
  1118. this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
  1119. this.dropdown.hide();
  1120. this.container.removeClass("select2-dropdown-open");
  1121. this.results.empty();
  1122. this.clearSearch();
  1123. this.search.removeClass("select2-active");
  1124. this.opts.element.trigger($.Event("select2-close"));
  1125. },
  1126. /**
  1127. * Opens control, sets input value, and updates results.
  1128. */
  1129. // abstract
  1130. externalSearch: function (term) {
  1131. this.open();
  1132. this.search.val(term);
  1133. this.updateResults(false);
  1134. },
  1135. // abstract
  1136. clearSearch: function () {
  1137. },
  1138. //abstract
  1139. getMaximumSelectionSize: function() {
  1140. return evaluate(this.opts.maximumSelectionSize);
  1141. },
  1142. // abstract
  1143. ensureHighlightVisible: function () {
  1144. var results = this.results, children, index, child, hb, rb, y, more;
  1145. index = this.highlight();
  1146. if (index < 0) return;
  1147. if (index == 0) {
  1148. // if the first element is highlighted scroll all the way to the top,
  1149. // that way any unselectable headers above it will also be scrolled
  1150. // into view
  1151. results.scrollTop(0);
  1152. return;
  1153. }
  1154. children = this.findHighlightableChoices().find('.select2-result-label');
  1155. child = $(children[index]);
  1156. hb = child.offset().top + child.outerHeight(true);
  1157. // if this is the last child lets also make sure select2-more-results is visible
  1158. if (index === children.length - 1) {
  1159. more = results.find("li.select2-more-results");
  1160. if (more.length > 0) {
  1161. hb = more.offset().top + more.outerHeight(true);
  1162. }
  1163. }
  1164. rb = results.offset().top + results.outerHeight(true);
  1165. if (hb > rb) {
  1166. results.scrollTop(results.scrollTop() + (hb - rb));
  1167. }
  1168. y = child.offset().top - results.offset().top;
  1169. // make sure the top of the element is visible
  1170. if (y < 0 && child.css('display') != 'none' ) {
  1171. results.scrollTop(results.scrollTop() + y); // y is negative
  1172. }
  1173. },
  1174. // abstract
  1175. findHighlightableChoices: function() {
  1176. return this.results.find(".select2-result-selectable:not(.select2-selected):not(.select2-disabled)");
  1177. },
  1178. // abstract
  1179. moveHighlight: function (delta) {
  1180. var choices = this.findHighlightableChoices(),
  1181. index = this.highlight();
  1182. while (index > -1 && index < choices.length) {
  1183. index += delta;
  1184. var choice = $(choices[index]);
  1185. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
  1186. this.highlight(index);
  1187. break;
  1188. }
  1189. }
  1190. },
  1191. // abstract
  1192. highlight: function (index) {
  1193. var choices = this.findHighlightableChoices(),
  1194. choice,
  1195. data;
  1196. if (arguments.length === 0) {
  1197. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  1198. }
  1199. if (index >= choices.length) index = choices.length - 1;
  1200. if (index < 0) index = 0;
  1201. this.removeHighlight();
  1202. choice = $(choices[index]);
  1203. choice.addClass("select2-highlighted");
  1204. this.ensureHighlightVisible();
  1205. data = choice.data("select2-data");
  1206. if (data) {
  1207. this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
  1208. }
  1209. },
  1210. removeHighlight: function() {
  1211. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1212. },
  1213. // abstract
  1214. countSelectableResults: function() {
  1215. return this.findHighlightableChoices().length;
  1216. },
  1217. // abstract
  1218. highlightUnderEvent: function (event) {
  1219. var el = $(event.target).closest(".select2-result-selectable");
  1220. if (el.length > 0 && !el.is(".select2-highlighted")) {
  1221. var choices = this.findHighlightableChoices();
  1222. this.highlight(choices.index(el));
  1223. } else if (el.length == 0) {
  1224. // if we are over an unselectable item remove all highlights
  1225. this.removeHighlight();
  1226. }
  1227. },
  1228. // abstract
  1229. loadMoreIfNeeded: function () {
  1230. var results = this.results,
  1231. more = results.find("li.select2-more-results"),
  1232. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  1233. offset = -1, // index of first element without data
  1234. page = this.resultsPage + 1,
  1235. self=this,
  1236. term=this.search.val(),
  1237. context=this.context;
  1238. if (more.length === 0) return;
  1239. below = more.offset().top - results.offset().top - results.height();
  1240. if (below <= this.opts.loadMorePadding) {
  1241. more.addClass("select2-active");
  1242. this.opts.query({
  1243. element: this.opts.element,
  1244. term: term,
  1245. page: page,
  1246. context: context,
  1247. matcher: this.opts.matcher,
  1248. callback: this.bind(function (data) {
  1249. // ignore a response if the select2 has been closed before it was received
  1250. if (!self.opened()) return;
  1251. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  1252. self.postprocessResults(data, false, false);
  1253. if (data.more===true) {
  1254. more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
  1255. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1256. } else {
  1257. more.remove();
  1258. }
  1259. self.positionDropdown();
  1260. self.resultsPage = page;
  1261. self.context = data.context;
  1262. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1263. })});
  1264. }
  1265. },
  1266. /**
  1267. * Default tokenizer function which does nothing
  1268. */
  1269. tokenize: function() {
  1270. },
  1271. /**
  1272. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  1273. */
  1274. // abstract
  1275. updateResults: function (initial) {
  1276. var search = this.search,
  1277. results = this.results,
  1278. opts = this.opts,
  1279. data,
  1280. self = this,
  1281. input,
  1282. term = search.val(),
  1283. lastTerm = $.data(this.container, "select2-last-term"),
  1284. // sequence number used to drop out-of-order responses
  1285. queryNumber;
  1286. // prevent duplicate queries against the same term
  1287. if (initial !== true && lastTerm && equal(term, lastTerm)) return;
  1288. $.data(this.container, "select2-last-term", term);
  1289. // if the search is currently hidden we do not alter the results
  1290. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  1291. return;
  1292. }
  1293. function postRender() {
  1294. search.removeClass("select2-active");
  1295. self.positionDropdown();
  1296. }
  1297. function render(html) {
  1298. results.html(html);
  1299. postRender();
  1300. }
  1301. queryNumber = ++this.queryCount;
  1302. var maxSelSize = this.getMaximumSelectionSize();
  1303. if (maxSelSize >=1) {
  1304. data = this.data();
  1305. if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  1306. render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>");
  1307. return;
  1308. }
  1309. }
  1310. if (search.val().length < opts.minimumInputLength) {
  1311. if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  1312. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  1313. } else {
  1314. render("");
  1315. }
  1316. if (initial && this.showSearch) this.showSearch(true);
  1317. return;
  1318. }
  1319. if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
  1320. if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
  1321. render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>");
  1322. } else {
  1323. render("");
  1324. }
  1325. return;
  1326. }
  1327. if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
  1328. render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
  1329. }
  1330. search.addClass("select2-active");
  1331. this.removeHighlight();
  1332. // give the tokenizer a chance to pre-process the input
  1333. input = this.tokenize();
  1334. if (input != undefined && input != null) {
  1335. search.val(input);
  1336. }
  1337. this.resultsPage = 1;
  1338. opts.query({
  1339. element: opts.element,
  1340. term: search.val(),
  1341. page: this.resultsPage,
  1342. context: null,
  1343. matcher: opts.matcher,
  1344. callback: this.bind(function (data) {
  1345. var def; // default choice
  1346. // ignore old responses
  1347. if (queryNumber != this.queryCount) {
  1348. return;
  1349. }
  1350. // ignore a response if the select2 has been closed before it was received
  1351. if (!this.opened()) {
  1352. this.search.removeClass("select2-active");
  1353. return;
  1354. }
  1355. // save context, if any
  1356. this.context = (data.context===undefined) ? null : data.context;
  1357. // create a default choice and prepend it to the list
  1358. if (this.opts.createSearchChoice && search.val() !== "") {
  1359. def = this.opts.createSearchChoice.call(self, search.val(), data.results);
  1360. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  1361. if ($(data.results).filter(
  1362. function () {
  1363. return equal(self.id(this), self.id(def));
  1364. }).length === 0) {
  1365. data.results.unshift(def);
  1366. }
  1367. }
  1368. }
  1369. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  1370. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  1371. return;
  1372. }
  1373. results.empty();
  1374. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  1375. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  1376. results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
  1377. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1378. }
  1379. this.postprocessResults(data, initial);
  1380. postRender();
  1381. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1382. })});
  1383. },
  1384. // abstract
  1385. cancel: function () {
  1386. this.close();
  1387. },
  1388. // abstract
  1389. blur: function () {
  1390. // if selectOnBlur == true, select the currently highlighted option
  1391. if (this.opts.selectOnBlur)
  1392. this.selectHighlighted({noFocus: true});
  1393. this.close();
  1394. this.container.removeClass("select2-container-active");
  1395. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  1396. if (this.search[0] === document.activeElement) { this.search.blur(); }
  1397. this.clearSearch();
  1398. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1399. },
  1400. // abstract
  1401. focusSearch: function () {
  1402. focus(this.search);
  1403. },
  1404. // abstract
  1405. selectHighlighted: function (options) {
  1406. var index=this.highlight(),
  1407. highlighted=this.results.find(".select2-highlighted"),
  1408. data = highlighted.closest('.select2-result').data("select2-data");
  1409. if (data) {
  1410. this.highlight(index);
  1411. this.onSelect(data, options);
  1412. } else if (options && options.noFocus) {
  1413. this.close();
  1414. }
  1415. },
  1416. // abstract
  1417. getPlaceholder: function () {
  1418. var placeholderOption;
  1419. return this.opts.element.attr("placeholder") ||
  1420. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1421. this.opts.element.data("placeholder") ||
  1422. this.opts.placeholder ||
  1423. ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
  1424. },
  1425. // abstract
  1426. getPlaceholderOption: function() {
  1427. if (this.select) {
  1428. var firstOption = this.select.children().first();
  1429. if (this.opts.placeholderOption !== undefined ) {
  1430. //Determine the placeholder option based on the specified placeholderOption setting
  1431. return (this.opts.placeholderOption === "first" && firstOption) ||
  1432. (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
  1433. } else if (firstOption.text() === "" && firstOption.val() === "") {
  1434. //No explicit placeholder option specified, use the first if it's blank
  1435. return firstOption;
  1436. }
  1437. }
  1438. },
  1439. /**
  1440. * Get the desired width for the container element. This is
  1441. * derived first from option `width` passed to select2, then
  1442. * the inline 'style' on the original element, and finally
  1443. * falls back to the jQuery calculated element width.
  1444. */
  1445. // abstract
  1446. initContainerWidth: function () {
  1447. function resolveContainerWidth() {
  1448. var style, attrs, matches, i, l;
  1449. if (this.opts.width === "off") {
  1450. return null;
  1451. } else if (this.opts.width === "element"){
  1452. return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
  1453. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1454. // check if there is inline style on the element that contains width
  1455. style = this.opts.element.attr('style');
  1456. if (style !== undefined) {
  1457. attrs = style.split(';');
  1458. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1459. matches = attrs[i].replace(/\s/g, '')
  1460. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
  1461. if (matches !== null && matches.length >= 1)
  1462. return matches[1];
  1463. }
  1464. }
  1465. if (this.opts.width === "resolve") {
  1466. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1467. // when attached to input type=hidden or elements hidden via css
  1468. style = this.opts.element.css('width');
  1469. if (style.indexOf("%") > 0) return style;
  1470. // finally, fallback on the calculated width of the element
  1471. return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
  1472. }
  1473. return null;
  1474. } else if ($.isFunction(this.opts.width)) {
  1475. return this.opts.width();
  1476. } else {
  1477. return this.opts.width;
  1478. }
  1479. };
  1480. var width = resolveContainerWidth.call(this);
  1481. if (width !== null) {
  1482. this.container.css("width", width);
  1483. }
  1484. }
  1485. });
  1486. SingleSelect2 = clazz(AbstractSelect2, {
  1487. // single
  1488. createContainer: function () {
  1489. var container = $(document.createElement("div")).attr({
  1490. "class": "select2-container"
  1491. }).html([
  1492. "<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>",
  1493. " <span class='select2-chosen'>&nbsp;</span><abbr class='select2-search-choice-close'></abbr>",
  1494. " <span class='select2-arrow'><b></b></span>",
  1495. "</a>",
  1496. "<input class='select2-focusser select2-offscreen' type='text'/>",
  1497. "<div class='select2-drop select2-display-none'>",
  1498. " <div class='select2-search'>",
  1499. " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'/>",
  1500. " </div>",
  1501. " <ul class='select2-results'>",
  1502. " </ul>",
  1503. "</div>"].join(""));
  1504. return container;
  1505. },
  1506. // single
  1507. enableInterface: function() {
  1508. if (this.parent.enableInterface.apply(this, arguments)) {
  1509. this.focusser.prop("disabled", !this.isInterfaceEnabled());
  1510. }
  1511. },
  1512. // single
  1513. opening: function () {
  1514. var el, range, len;
  1515. if (this.opts.minimumResultsForSearch >= 0) {
  1516. this.showSearch(true);
  1517. }
  1518. this.parent.opening.apply(this, arguments);
  1519. if (this.showSearchInput !== false) {
  1520. // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
  1521. // all other browsers handle this just fine
  1522. this.search.val(this.focusser.val());
  1523. }
  1524. this.search.focus();
  1525. // move the cursor to the end after focussing, otherwise it will be at the beginning and
  1526. // new text will appear *before* focusser.val()
  1527. el = this.search.get(0);
  1528. if (el.createTextRange) {
  1529. range = el.createTextRange();
  1530. range.collapse(false);
  1531. range.select();
  1532. } else if (el.setSelectionRange) {
  1533. len = this.search.val().length;
  1534. el.setSelectionRange(len, len);
  1535. }
  1536. this.focusser.prop("disabled", true).val("");
  1537. this.updateResults(true);
  1538. this.opts.element.trigger($.Event("select2-open"));
  1539. },
  1540. // single
  1541. close: function () {
  1542. if (!this.opened()) return;
  1543. this.parent.close.apply(this, arguments);
  1544. this.focusser.removeAttr("disabled");
  1545. this.focusser.focus();
  1546. },
  1547. // single
  1548. focus: function () {
  1549. if (this.opened()) {
  1550. this.close();
  1551. } else {
  1552. this.focusser.removeAttr("disabled");
  1553. this.focusser.focus();
  1554. }
  1555. },
  1556. // single
  1557. isFocused: function () {
  1558. return this.container.hasClass("select2-container-active");
  1559. },
  1560. // single
  1561. cancel: function () {
  1562. this.parent.cancel.apply(this, arguments);
  1563. this.focusser.removeAttr("disabled");
  1564. this.focusser.focus();
  1565. },
  1566. // single
  1567. initContainer: function () {
  1568. var selection,
  1569. container = this.container,
  1570. dropdown = this.dropdown;
  1571. if (this.opts.minimumResultsForSearch < 0) {
  1572. this.showSearch(false);
  1573. } else {
  1574. this.showSearch(true);
  1575. }
  1576. this.selection = selection = container.find(".select2-choice");
  1577. this.focusser = container.find(".select2-focusser");
  1578. // rewrite labels from original element to focusser
  1579. this.focusser.attr("id", "s2id_autogen"+nextUid());
  1580. $("label[for='" + this.opts.element.attr("id") + "']")
  1581. .attr('for', this.focusser.attr('id'));
  1582. this.focusser.attr("tabindex", this.elementTabIndex);
  1583. this.search.on("keydown", this.bind(function (e) {
  1584. if (!this.isInterfaceEnabled()) return;
  1585. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1586. // prevent the page from scrolling
  1587. killEvent(e);
  1588. return;
  1589. }
  1590. switch (e.which) {
  1591. case KEY.UP:
  1592. case KEY.DOWN:
  1593. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1594. killEvent(e);
  1595. return;
  1596. case KEY.ENTER:
  1597. this.selectHighlighted();
  1598. killEvent(e);
  1599. return;
  1600. case KEY.TAB:
  1601. this.selectHighlighted({noFocus: true});
  1602. return;
  1603. case KEY.ESC:
  1604. this.cancel(e);
  1605. killEvent(e);
  1606. return;
  1607. }
  1608. }));
  1609. this.search.on("blur", this.bind(function(e) {
  1610. // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
  1611. // without this the search field loses focus which is annoying
  1612. if (document.activeElement === this.body().get(0)) {
  1613. window.setTimeout(this.bind(function() {
  1614. this.search.focus();
  1615. }), 0);
  1616. }
  1617. }));
  1618. this.focusser.on("keydown", this.bind(function (e) {
  1619. if (!this.isInterfaceEnabled()) return;
  1620. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1621. return;
  1622. }
  1623. if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
  1624. killEvent(e);
  1625. return;
  1626. }
  1627. if (e.which == KEY.DOWN || e.which == KEY.UP
  1628. || (e.which == KEY.ENTER && this.opts.openOnEnter)) {
  1629. if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;
  1630. this.open();
  1631. killEvent(e);
  1632. return;
  1633. }
  1634. if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
  1635. if (this.opts.allowClear) {
  1636. this.clear();
  1637. }
  1638. killEvent(e);
  1639. return;
  1640. }
  1641. }));
  1642. installKeyUpChangeEvent(this.focusser);
  1643. this.focusser.on("keyup-change input", this.bind(function(e) {
  1644. if (this.opts.minimumResultsForSearch >= 0) {
  1645. e.stopPropagation();
  1646. if (this.opened()) return;
  1647. this.open();
  1648. }
  1649. }));
  1650. selection.on("mousedown", "abbr", this.bind(function (e) {
  1651. if (!this.isInterfaceEnabled()) return;
  1652. this.clear();
  1653. killEventImmediately(e);
  1654. this.close();
  1655. this.selection.focus();
  1656. }));
  1657. selection.on("mousedown", this.bind(function (e) {
  1658. if (!this.container.hasClass("select2-container-active")) {
  1659. this.opts.element.trigger($.Event("select2-focus"));
  1660. }
  1661. if (this.opened()) {
  1662. this.close();
  1663. } else if (this.isInterfaceEnabled()) {
  1664. this.open();
  1665. }
  1666. killEvent(e);
  1667. }));
  1668. dropdown.on("mousedown", this.bind(function() { this.search.focus(); }));
  1669. selection.on("focus", this.bind(function(e) {
  1670. killEvent(e);
  1671. }));
  1672. this.focusser.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. })).on("blur", this.bind(function() {
  1678. if (!this.opened()) {
  1679. this.container.removeClass("select2-container-active");
  1680. this.opts.element.trigger($.Event("select2-blur"));
  1681. }
  1682. }));
  1683. this.search.on("focus", this.bind(function(){
  1684. if (!this.container.hasClass("select2-container-active")) {
  1685. this.opts.element.trigger($.Event("select2-focus"));
  1686. }
  1687. this.container.addClass("select2-container-active");
  1688. }));
  1689. this.initContainerWidth();
  1690. this.opts.element.addClass("select2-offscreen");
  1691. this.setPlaceholder();
  1692. },
  1693. // single
  1694. clear: function(triggerChange) {
  1695. var data=this.selection.data("select2-data");
  1696. if (data) { // guard against queued quick consecutive clicks
  1697. var placeholderOption = this.getPlaceholderOption();
  1698. this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
  1699. this.selection.find(".select2-chosen").empty();
  1700. this.selection.removeData("select2-data");
  1701. this.setPlaceholder();
  1702. if (triggerChange !== false){
  1703. this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
  1704. this.triggerChange({removed:data});
  1705. }
  1706. }
  1707. },
  1708. /**
  1709. * Sets selection based on source element's value
  1710. */
  1711. // single
  1712. initSelection: function () {
  1713. var selected;
  1714. if (this.isPlaceholderOptionSelected()) {
  1715. this.updateSelection([]);
  1716. this.close();
  1717. this.setPlaceholder();
  1718. } else {
  1719. var self = this;
  1720. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1721. if (selected !== undefined && selected !== null) {
  1722. self.updateSelection(selected);
  1723. self.close();
  1724. self.setPlaceholder();
  1725. }
  1726. });
  1727. }
  1728. },
  1729. isPlaceholderOptionSelected: function() {
  1730. var placeholderOption;
  1731. return this.opts.placeholder &&
  1732. ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.is(':selected')) ||
  1733. (this.opts.element.val() === "") ||
  1734. (this.opts.element.val() === undefined) ||
  1735. (this.opts.element.val() === null);
  1736. },
  1737. // single
  1738. prepareOpts: function () {
  1739. var opts = this.parent.prepareOpts.apply(this, arguments),
  1740. self=this;
  1741. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1742. // install the selection initializer
  1743. opts.initSelection = function (element, callback) {
  1744. var selected = element.find(":selected");
  1745. // a single select box always has a value, no need to null check 'selected'
  1746. callback(self.optionToData(selected));
  1747. };
  1748. } else if ("data" in opts) {
  1749. // install default initSelection when applied to hidden input and data is local
  1750. opts.initSelection = opts.initSelection || function (element, callback) {
  1751. var id = element.val();
  1752. //search in data by id, storing the actual matching item
  1753. var match = null;
  1754. opts.query({
  1755. matcher: function(term, text, el){
  1756. var is_match = equal(id, opts.id(el));
  1757. if (is_match) {
  1758. match = el;
  1759. }
  1760. return is_match;
  1761. },
  1762. callback: !$.isFunction(callback) ? $.noop : function() {
  1763. callback(match);
  1764. }
  1765. });
  1766. };
  1767. }
  1768. return opts;
  1769. },
  1770. // single
  1771. getPlaceholder: function() {
  1772. // if a placeholder is specified on a single select without a valid placeholder option ignore it
  1773. if (this.select) {
  1774. if (this.getPlaceholderOption() === undefined) {
  1775. return undefined;
  1776. }
  1777. }
  1778. return this.parent.getPlaceholder.apply(this, arguments);
  1779. },
  1780. // single
  1781. setPlaceholder: function () {
  1782. var placeholder = this.getPlaceholder();
  1783. if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {
  1784. // check for a placeholder option if attached to a select
  1785. if (this.select && this.getPlaceholderOption() === undefined) return;
  1786. this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));
  1787. this.selection.addClass("select2-default");
  1788. this.container.removeClass("select2-allowclear");
  1789. }
  1790. },
  1791. // single
  1792. postprocessResults: function (data, initial, noHighlightUpdate) {
  1793. var selected = 0, self = this, showSearchInput = true;
  1794. // find the selected element in the result list
  1795. this.findHighlightableChoices().each2(function (i, elm) {
  1796. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1797. selected = i;
  1798. return false;
  1799. }
  1800. });
  1801. // and highlight it
  1802. if (noHighlightUpdate !== false) {
  1803. if (initial === true && selected >= 0) {
  1804. this.highlight(selected);
  1805. } else {
  1806. this.highlight(0);
  1807. }
  1808. }
  1809. // hide the search box if this is the first we got the results and there are enough of them for search
  1810. if (initial === true) {
  1811. var min = this.opts.minimumResultsForSearch;
  1812. if (min >= 0) {
  1813. this.showSearch(countResults(data.results) >= min);
  1814. }
  1815. }
  1816. },
  1817. // single
  1818. showSearch: function(showSearchInput) {
  1819. if (this.showSearchInput === showSearchInput) return;
  1820. this.showSearchInput = showSearchInput;
  1821. this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
  1822. this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
  1823. //add "select2-with-searchbox" to the container if search box is shown
  1824. $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
  1825. },
  1826. // single
  1827. onSelect: function (data, options) {
  1828. if (!this.triggerSelect(data)) { return; }
  1829. var old = this.opts.element.val(),
  1830. oldData = this.data();
  1831. this.opts.element.val(this.id(data));
  1832. this.updateSelection(data);
  1833. this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
  1834. this.close();
  1835. if (!options || !options.noFocus)
  1836. this.selection.focus();
  1837. if (!equal(old, this.id(data))) { this.triggerChange({added:data,removed:oldData}); }
  1838. },
  1839. // single
  1840. updateSelection: function (data) {
  1841. var container=this.selection.find(".select2-chosen"), formatted, cssClass;
  1842. this.selection.data("select2-data", data);
  1843. container.empty();
  1844. formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
  1845. if (formatted !== undefined) {
  1846. container.append(formatted);
  1847. }
  1848. cssClass=this.opts.formatSelectionCssClass(data, container);
  1849. if (cssClass !== undefined) {
  1850. container.addClass(cssClass);
  1851. }
  1852. this.selection.removeClass("select2-default");
  1853. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1854. this.container.addClass("select2-allowclear");
  1855. }
  1856. },
  1857. // single
  1858. val: function () {
  1859. var val,
  1860. triggerChange = false,
  1861. data = null,
  1862. self = this,
  1863. oldData = this.data();
  1864. if (arguments.length === 0) {
  1865. return this.opts.element.val();
  1866. }
  1867. val = arguments[0];
  1868. if (arguments.length > 1) {
  1869. triggerChange = arguments[1];
  1870. }
  1871. if (this.select) {
  1872. this.select
  1873. .val(val)
  1874. .find(":selected").each2(function (i, elm) {
  1875. data = self.optionToData(elm);
  1876. return false;
  1877. });
  1878. this.updateSelection(data);
  1879. this.setPlaceholder();
  1880. if (triggerChange) {
  1881. this.triggerChange({added: data, removed:oldData});
  1882. }
  1883. } else {
  1884. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  1885. if (!val && val !== 0) {
  1886. this.clear(triggerChange);
  1887. return;
  1888. }
  1889. if (this.opts.initSelection === undefined) {
  1890. throw new Error("cannot call val() if initSelection() is not defined");
  1891. }
  1892. this.opts.element.val(val);
  1893. this.opts.initSelection(this.opts.element, function(data){
  1894. self.opts.element.val(!data ? "" : self.id(data));
  1895. self.updateSelection(data);
  1896. self.setPlaceholder();
  1897. if (triggerChange) {
  1898. self.triggerChange({added: data, removed:oldData});
  1899. }
  1900. });
  1901. }
  1902. },
  1903. // single
  1904. clearSearch: function () {
  1905. this.search.val("");
  1906. this.focusser.val("");
  1907. },
  1908. // single
  1909. data: function(value, triggerChange) {
  1910. var data;
  1911. if (arguments.length === 0) {
  1912. data = this.selection.data("select2-data");
  1913. if (data == undefined) data = null;
  1914. return data;
  1915. } else {
  1916. if (!value || value === "") {
  1917. this.clear(triggerChange);
  1918. } else {
  1919. data = this.data();
  1920. this.opts.element.val(!value ? "" : this.id(value));
  1921. this.updateSelection(value);
  1922. if (triggerChange) {
  1923. this.triggerChange({added: value, removed:data});
  1924. }
  1925. }
  1926. }
  1927. }
  1928. });
  1929. MultiSelect2 = clazz(AbstractSelect2, {
  1930. // multi
  1931. createContainer: function () {
  1932. var container = $(document.createElement("div")).attr({
  1933. "class": "select2-container select2-container-multi"
  1934. }).html([
  1935. "<ul class='select2-choices'>",
  1936. " <li class='select2-search-field'>",
  1937. " <input type='text' autocomplete='off' autocorrect='off' autocapitilize='off' spellcheck='false' class='select2-input'>",
  1938. " </li>",
  1939. "</ul>",
  1940. "<div class='select2-drop select2-drop-multi select2-display-none'>",
  1941. " <ul class='select2-results'>",
  1942. " </ul>",
  1943. "</div>"].join(""));
  1944. return container;
  1945. },
  1946. // multi
  1947. prepareOpts: function () {
  1948. var opts = this.parent.prepareOpts.apply(this, arguments),
  1949. self=this;
  1950. // TODO validate placeholder is a string if specified
  1951. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1952. // install sthe selection initializer
  1953. opts.initSelection = function (element, callback) {
  1954. var data = [];
  1955. element.find(":selected").each2(function (i, elm) {
  1956. data.push(self.optionToData(elm));
  1957. });
  1958. callback(data);
  1959. };
  1960. } else if ("data" in opts) {
  1961. // install default initSelection when applied to hidden input and data is local
  1962. opts.initSelection = opts.initSelection || function (element, callback) {
  1963. var ids = splitVal(element.val(), opts.separator);
  1964. //search in data by array of ids, storing matching items in a list
  1965. var matches = [];
  1966. opts.query({
  1967. matcher: function(term, text, el){
  1968. var is_match = $.grep(ids, function(id) {
  1969. return equal(id, opts.id(el));
  1970. }).length;
  1971. if (is_match) {
  1972. matches.push(el);
  1973. }
  1974. return is_match;
  1975. },
  1976. callback: !$.isFunction(callback) ? $.noop : function() {
  1977. // reorder matches based on the order they appear in the ids array because right now
  1978. // they are in the order in which they appear in data array
  1979. var ordered = [];
  1980. for (var i = 0; i < ids.length; i++) {
  1981. var id = ids[i];
  1982. for (var j = 0; j < matches.length; j++) {
  1983. var match = matches[j];
  1984. if (equal(id, opts.id(match))) {
  1985. ordered.push(match);
  1986. matches.splice(j, 1);
  1987. break;
  1988. }
  1989. }
  1990. }
  1991. callback(ordered);
  1992. }
  1993. });
  1994. };
  1995. }
  1996. return opts;
  1997. },
  1998. selectChoice: function (choice) {
  1999. var selected = this.container.find(".select2-search-choice-focus");
  2000. if (selected.length && choice && choice[0] == selected[0]) {
  2001. } else {
  2002. if (selected.length) {
  2003. this.opts.element.trigger("choice-deselected", selected);
  2004. }
  2005. selected.removeClass("select2-search-choice-focus");
  2006. if (choice && choice.length) {
  2007. this.close();
  2008. choice.addClass("select2-search-choice-focus");
  2009. this.opts.element.trigger("choice-selected", choice);
  2010. }
  2011. }
  2012. },
  2013. // multi
  2014. initContainer: function () {
  2015. var selector = ".select2-choices", selection;
  2016. this.searchContainer = this.container.find(".select2-search-field");
  2017. this.selection = selection = this.container.find(selector);
  2018. var _this = this;
  2019. this.selection.on("click", ".select2-search-choice", function (e) {
  2020. //killEvent(e);
  2021. _this.search[0].focus();
  2022. _this.selectChoice($(this));
  2023. });
  2024. // rewrite labels from original element to focusser
  2025. this.search.attr("id", "s2id_autogen"+nextUid());
  2026. $("label[for='" + this.opts.element.attr("id") + "']")
  2027. .attr('for', this.search.attr('id'));
  2028. this.search.on("input paste", this.bind(function() {
  2029. if (!this.isInterfaceEnabled()) return;
  2030. if (!this.opened()) {
  2031. this.open();
  2032. }
  2033. }));
  2034. this.search.attr("tabindex", this.elementTabIndex);
  2035. this.keydowns = 0;
  2036. this.search.on("keydown", this.bind(function (e) {
  2037. if (!this.isInterfaceEnabled()) return;
  2038. ++this.keydowns;
  2039. var selected = selection.find(".select2-search-choice-focus");
  2040. var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
  2041. var next = selected.next(".select2-search-choice:not(.select2-locked)");
  2042. var pos = getCursorInfo(this.search);
  2043. if (selected.length &&
  2044. (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
  2045. var selectedChoice = selected;
  2046. if (e.which == KEY.LEFT && prev.length) {
  2047. selectedChoice = prev;
  2048. }
  2049. else if (e.which == KEY.RIGHT) {
  2050. selectedChoice = next.length ? next : null;
  2051. }
  2052. else if (e.which === KEY.BACKSPACE) {
  2053. this.unselect(selected.first());
  2054. this.search.width(10);
  2055. selectedChoice = prev.length ? prev : next;
  2056. } else if (e.which == KEY.DELETE) {
  2057. this.unselect(selected.first());
  2058. this.search.width(10);
  2059. selectedChoice = next.length ? next : null;
  2060. } else if (e.which == KEY.ENTER) {
  2061. selectedChoice = null;
  2062. }
  2063. this.selectChoice(selectedChoice);
  2064. killEvent(e);
  2065. if (!selectedChoice || !selectedChoice.length) {
  2066. this.open();
  2067. }
  2068. return;
  2069. } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
  2070. || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {
  2071. this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
  2072. killEvent(e);
  2073. return;
  2074. } else {
  2075. this.selectChoice(null);
  2076. }
  2077. if (this.opened()) {
  2078. switch (e.which) {
  2079. case KEY.UP:
  2080. case KEY.DOWN:
  2081. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  2082. killEvent(e);
  2083. return;
  2084. case KEY.ENTER:
  2085. this.selectHighlighted();
  2086. killEvent(e);
  2087. return;
  2088. case KEY.TAB:
  2089. this.selectHighlighted({noFocus:true});
  2090. this.close();
  2091. return;
  2092. case KEY.ESC:
  2093. this.cancel(e);
  2094. killEvent(e);
  2095. return;
  2096. }
  2097. }
  2098. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  2099. || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  2100. return;
  2101. }
  2102. if (e.which === KEY.ENTER) {
  2103. if (this.opts.openOnEnter === false) {
  2104. return;
  2105. } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
  2106. return;
  2107. }
  2108. }
  2109. this.open();
  2110. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  2111. // prevent the page from scrolling
  2112. killEvent(e);
  2113. }
  2114. if (e.which === KEY.ENTER) {
  2115. // prevent form from being submitted
  2116. killEvent(e);
  2117. }
  2118. }));
  2119. this.search.on("keyup", this.bind(function (e) {
  2120. this.keydowns = 0;
  2121. this.resizeSearch();
  2122. })
  2123. );
  2124. this.search.on("blur", this.bind(function(e) {
  2125. this.container.removeClass("select2-container-active");
  2126. this.search.removeClass("select2-focused");
  2127. this.selectChoice(null);
  2128. if (!this.opened()) this.clearSearch();
  2129. e.stopImmediatePropagation();
  2130. this.opts.element.trigger($.Event("select2-blur"));
  2131. }));
  2132. this.container.on("click", selector, this.bind(function (e) {
  2133. if (!this.isInterfaceEnabled()) return;
  2134. if ($(e.target).closest(".select2-search-choice").length > 0) {
  2135. // clicked inside a select2 search choice, do not open
  2136. return;
  2137. }
  2138. this.selectChoice(null);
  2139. this.clearPlaceholder();
  2140. if (!this.container.hasClass("select2-container-active")) {
  2141. this.opts.element.trigger($.Event("select2-focus"));
  2142. }
  2143. this.open();
  2144. this.focusSearch();
  2145. e.preventDefault();
  2146. }));
  2147. this.container.on("focus", selector, this.bind(function () {
  2148. if (!this.isInterfaceEnabled()) return;
  2149. if (!this.container.hasClass("select2-container-active")) {
  2150. this.opts.element.trigger($.Event("select2-focus"));
  2151. }
  2152. this.container.addClass("select2-container-active");
  2153. this.dropdown.addClass("select2-drop-active");
  2154. this.clearPlaceholder();
  2155. }));
  2156. this.initContainerWidth();
  2157. this.opts.element.addClass("select2-offscreen");
  2158. // set the placeholder if necessary
  2159. this.clearSearch();
  2160. },
  2161. // multi
  2162. enableInterface: function() {
  2163. if (this.parent.enableInterface.apply(this, arguments)) {
  2164. this.search.prop("disabled", !this.isInterfaceEnabled());
  2165. }
  2166. },
  2167. // multi
  2168. initSelection: function () {
  2169. var data;
  2170. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  2171. this.updateSelection([]);
  2172. this.close();
  2173. // set the placeholder if necessary
  2174. this.clearSearch();
  2175. }
  2176. if (this.select || this.opts.element.val() !== "") {
  2177. var self = this;
  2178. this.opts.initSelection.call(null, this.opts.element, function(data){
  2179. if (data !== undefined && data !== null) {
  2180. self.updateSelection(data);
  2181. self.close();
  2182. // set the placeholder if necessary
  2183. self.clearSearch();
  2184. }
  2185. });
  2186. }
  2187. },
  2188. // multi
  2189. clearSearch: function () {
  2190. var placeholder = this.getPlaceholder(),
  2191. maxWidth = this.getMaxSearchWidth();
  2192. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  2193. this.search.val(placeholder).addClass("select2-default");
  2194. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  2195. // 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
  2196. this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
  2197. } else {
  2198. this.search.val("").width(10);
  2199. }
  2200. },
  2201. // multi
  2202. clearPlaceholder: function () {
  2203. if (this.search.hasClass("select2-default")) {
  2204. this.search.val("").removeClass("select2-default");
  2205. }
  2206. },
  2207. // multi
  2208. opening: function () {
  2209. this.clearPlaceholder(); // should be done before super so placeholder is not used to search
  2210. this.resizeSearch();
  2211. this.parent.opening.apply(this, arguments);
  2212. this.focusSearch();
  2213. this.updateResults(true);
  2214. this.search.focus();
  2215. this.opts.element.trigger($.Event("select2-open"));
  2216. },
  2217. // multi
  2218. close: function () {
  2219. if (!this.opened()) return;
  2220. this.parent.close.apply(this, arguments);
  2221. },
  2222. // multi
  2223. focus: function () {
  2224. this.close();
  2225. this.search.focus();
  2226. },
  2227. // multi
  2228. isFocused: function () {
  2229. return this.search.hasClass("select2-focused");
  2230. },
  2231. // multi
  2232. updateSelection: function (data) {
  2233. var ids = [], filtered = [], self = this;
  2234. // filter out duplicates
  2235. $(data).each(function () {
  2236. if (indexOf(self.id(this), ids) < 0) {
  2237. ids.push(self.id(this));
  2238. filtered.push(this);
  2239. }
  2240. });
  2241. data = filtered;
  2242. this.selection.find(".select2-search-choice").remove();
  2243. $(data).each(function () {
  2244. self.addSelectedChoice(this);
  2245. });
  2246. self.postprocessResults();
  2247. },
  2248. // multi
  2249. tokenize: function() {
  2250. var input = this.search.val();
  2251. input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
  2252. if (input != null && input != undefined) {
  2253. this.search.val(input);
  2254. if (input.length > 0) {
  2255. this.open();
  2256. }
  2257. }
  2258. },
  2259. // multi
  2260. onSelect: function (data, options) {
  2261. if (!this.triggerSelect(data)) { return; }
  2262. this.addSelectedChoice(data);
  2263. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  2264. if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true);
  2265. if (this.opts.closeOnSelect) {
  2266. this.close();
  2267. this.search.width(10);
  2268. } else {
  2269. if (this.countSelectableResults()>0) {
  2270. this.search.width(10);
  2271. this.resizeSearch();
  2272. if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
  2273. // if we reached max selection size repaint the results so choices
  2274. // are replaced with the max selection reached message
  2275. this.updateResults(true);
  2276. }
  2277. this.positionDropdown();
  2278. } else {
  2279. // if nothing left to select close
  2280. this.close();
  2281. this.search.width(10);
  2282. }
  2283. }
  2284. // since its not possible to select an element that has already been
  2285. // added we do not need to check if this is a new element before firing change
  2286. this.triggerChange({ added: data });
  2287. if (!options || !options.noFocus)
  2288. this.focusSearch();
  2289. },
  2290. // multi
  2291. cancel: function () {
  2292. this.close();
  2293. this.focusSearch();
  2294. },
  2295. addSelectedChoice: function (data) {
  2296. var enableChoice = !data.locked,
  2297. enabledItem = $(
  2298. "<li class='select2-search-choice'>" +
  2299. " <div></div>" +
  2300. " <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
  2301. "</li>"),
  2302. disabledItem = $(
  2303. "<li class='select2-search-choice select2-locked'>" +
  2304. "<div></div>" +
  2305. "</li>");
  2306. var choice = enableChoice ? enabledItem : disabledItem,
  2307. id = this.id(data),
  2308. val = this.getVal(),
  2309. formatted,
  2310. cssClass;
  2311. formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
  2312. if (formatted != undefined) {
  2313. choice.find("div").replaceWith("<div>"+formatted+"</div>");
  2314. }
  2315. cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
  2316. if (cssClass != undefined) {
  2317. choice.addClass(cssClass);
  2318. }
  2319. if(enableChoice){
  2320. choice.find(".select2-search-choice-close")
  2321. .on("mousedown", killEvent)
  2322. .on("click dblclick", this.bind(function (e) {
  2323. if (!this.isInterfaceEnabled()) return;
  2324. $(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
  2325. this.unselect($(e.target));
  2326. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  2327. this.close();
  2328. this.focusSearch();
  2329. })).dequeue();
  2330. killEvent(e);
  2331. })).on("focus", this.bind(function () {
  2332. if (!this.isInterfaceEnabled()) return;
  2333. this.container.addClass("select2-container-active");
  2334. this.dropdown.addClass("select2-drop-active");
  2335. }));
  2336. }
  2337. choice.data("select2-data", data);
  2338. choice.insertBefore(this.searchContainer);
  2339. val.push(id);
  2340. this.setVal(val);
  2341. },
  2342. // multi
  2343. unselect: function (selected) {
  2344. var val = this.getVal(),
  2345. data,
  2346. index;
  2347. selected = selected.closest(".select2-search-choice");
  2348. if (selected.length === 0) {
  2349. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  2350. }
  2351. data = selected.data("select2-data");
  2352. if (!data) {
  2353. // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
  2354. // and invoked on an element already removed
  2355. return;
  2356. }
  2357. index = indexOf(this.id(data), val);
  2358. if (index >= 0) {
  2359. val.splice(index, 1);
  2360. this.setVal(val);
  2361. if (this.select) this.postprocessResults();
  2362. }
  2363. selected.remove();
  2364. this.opts.element.trigger({ type: "removed", val: this.id(data), choice: data });
  2365. this.triggerChange({ removed: data });
  2366. },
  2367. // multi
  2368. postprocessResults: function (data, initial, noHighlightUpdate) {
  2369. var val = this.getVal(),
  2370. choices = this.results.find(".select2-result"),
  2371. compound = this.results.find(".select2-result-with-children"),
  2372. self = this;
  2373. choices.each2(function (i, choice) {
  2374. var id = self.id(choice.data("select2-data"));
  2375. if (indexOf(id, val) >= 0) {
  2376. choice.addClass("select2-selected");
  2377. // mark all children of the selected parent as selected
  2378. choice.find(".select2-result-selectable").addClass("select2-selected");
  2379. }
  2380. });
  2381. compound.each2(function(i, choice) {
  2382. // hide an optgroup if it doesnt have any selectable children
  2383. if (!choice.is('.select2-result-selectable')
  2384. && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
  2385. choice.addClass("select2-selected");
  2386. }
  2387. });
  2388. if (this.highlight() == -1 && noHighlightUpdate !== false){
  2389. self.highlight(0);
  2390. }
  2391. //If all results are chosen render formatNoMAtches
  2392. if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
  2393. if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
  2394. if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
  2395. this.results.append("<li class='select2-no-results'>" + self.opts.formatNoMatches(self.search.val()) + "</li>");
  2396. }
  2397. }
  2398. }
  2399. },
  2400. // multi
  2401. getMaxSearchWidth: function() {
  2402. return this.selection.width() - getSideBorderPadding(this.search);
  2403. },
  2404. // multi
  2405. resizeSearch: function () {
  2406. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  2407. sideBorderPadding = getSideBorderPadding(this.search);
  2408. minimumWidth = measureTextWidth(this.search) + 10;
  2409. left = this.search.offset().left;
  2410. maxWidth = this.selection.width();
  2411. containerLeft = this.selection.offset().left;
  2412. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  2413. if (searchWidth < minimumWidth) {
  2414. searchWidth = maxWidth - sideBorderPadding;
  2415. }
  2416. if (searchWidth < 40) {
  2417. searchWidth = maxWidth - sideBorderPadding;
  2418. }
  2419. if (searchWidth <= 0) {
  2420. searchWidth = minimumWidth;
  2421. }
  2422. this.search.width(searchWidth);
  2423. },
  2424. // multi
  2425. getVal: function () {
  2426. var val;
  2427. if (this.select) {
  2428. val = this.select.val();
  2429. return val === null ? [] : val;
  2430. } else {
  2431. val = this.opts.element.val();
  2432. return splitVal(val, this.opts.separator);
  2433. }
  2434. },
  2435. // multi
  2436. setVal: function (val) {
  2437. var unique;
  2438. if (this.select) {
  2439. this.select.val(val);
  2440. } else {
  2441. unique = [];
  2442. // filter out duplicates
  2443. $(val).each(function () {
  2444. if (indexOf(this, unique) < 0) unique.push(this);
  2445. });
  2446. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  2447. }
  2448. },
  2449. // multi
  2450. buildChangeDetails: function (old, current) {
  2451. var current = current.slice(0),
  2452. old = old.slice(0);
  2453. // remove intersection from each array
  2454. for (var i = 0; i < current.length; i++) {
  2455. for (var j = 0; j < old.length; j++) {
  2456. if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
  2457. current.splice(i, 1);
  2458. i--;
  2459. old.splice(j, 1);
  2460. j--;
  2461. }
  2462. }
  2463. }
  2464. return {added: current, removed: old};
  2465. },
  2466. // multi
  2467. val: function (val, triggerChange) {
  2468. var oldData, self=this, changeDetails;
  2469. if (arguments.length === 0) {
  2470. return this.getVal();
  2471. }
  2472. oldData=this.data();
  2473. if (!oldData.length) oldData=[];
  2474. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2475. if (!val && val !== 0) {
  2476. this.opts.element.val("");
  2477. this.updateSelection([]);
  2478. this.clearSearch();
  2479. if (triggerChange) {
  2480. this.triggerChange({added: this.data(), removed: oldData});
  2481. }
  2482. return;
  2483. }
  2484. // val is a list of ids
  2485. this.setVal(val);
  2486. if (this.select) {
  2487. this.opts.initSelection(this.select, this.bind(this.updateSelection));
  2488. if (triggerChange) {
  2489. this.triggerChange(this.buildChangeDetails(oldData, this.data()));
  2490. }
  2491. } else {
  2492. if (this.opts.initSelection === undefined) {
  2493. throw new Error("val() cannot be called if initSelection() is not defined");
  2494. }
  2495. this.opts.initSelection(this.opts.element, function(data){
  2496. var ids=$.map(data, self.id);
  2497. self.setVal(ids);
  2498. self.updateSelection(data);
  2499. self.clearSearch();
  2500. if (triggerChange) {
  2501. self.triggerChange(this.buildChangeDetails(oldData, this.data()));
  2502. }
  2503. });
  2504. }
  2505. this.clearSearch();
  2506. },
  2507. // multi
  2508. onSortStart: function() {
  2509. if (this.select) {
  2510. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  2511. }
  2512. // collapse search field into 0 width so its container can be collapsed as well
  2513. this.search.width(0);
  2514. // hide the container
  2515. this.searchContainer.hide();
  2516. },
  2517. // multi
  2518. onSortEnd:function() {
  2519. var val=[], self=this;
  2520. // show search and move it to the end of the list
  2521. this.searchContainer.show();
  2522. // make sure the search container is the last item in the list
  2523. this.searchContainer.appendTo(this.searchContainer.parent());
  2524. // since we collapsed the width in dragStarted, we resize it here
  2525. this.resizeSearch();
  2526. // update selection
  2527. this.selection.find(".select2-search-choice").each(function() {
  2528. val.push(self.opts.id($(this).data("select2-data")));
  2529. });
  2530. this.setVal(val);
  2531. this.triggerChange();
  2532. },
  2533. // multi
  2534. data: function(values, triggerChange) {
  2535. var self=this, ids, old;
  2536. if (arguments.length === 0) {
  2537. return this.selection
  2538. .find(".select2-search-choice")
  2539. .map(function() { return $(this).data("select2-data"); })
  2540. .get();
  2541. } else {
  2542. old = this.data();
  2543. if (!values) { values = []; }
  2544. ids = $.map(values, function(e) { return self.opts.id(e); });
  2545. this.setVal(ids);
  2546. this.updateSelection(values);
  2547. this.clearSearch();
  2548. if (triggerChange) {
  2549. this.triggerChange(this.buildChangeDetails(old, this.data()));
  2550. }
  2551. }
  2552. }
  2553. });
  2554. $.fn.select2 = function () {
  2555. var args = Array.prototype.slice.call(arguments, 0),
  2556. opts,
  2557. select2,
  2558. method, value, multiple,
  2559. allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"],
  2560. valueMethods = ["opened", "isFocused", "container", "dropdown"],
  2561. propertyMethods = ["val", "data"],
  2562. methodsMap = { search: "externalSearch" };
  2563. this.each(function () {
  2564. if (args.length === 0 || typeof(args[0]) === "object") {
  2565. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  2566. opts.element = $(this);
  2567. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2568. multiple = opts.element.prop("multiple");
  2569. } else {
  2570. multiple = opts.multiple || false;
  2571. if ("tags" in opts) {opts.multiple = multiple = true;}
  2572. }
  2573. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  2574. select2.init(opts);
  2575. } else if (typeof(args[0]) === "string") {
  2576. if (indexOf(args[0], allowedMethods) < 0) {
  2577. throw "Unknown method: " + args[0];
  2578. }
  2579. value = undefined;
  2580. select2 = $(this).data("select2");
  2581. if (select2 === undefined) return;
  2582. method=args[0];
  2583. if (method === "container") {
  2584. value = select2.container;
  2585. } else if (method === "dropdown") {
  2586. value = select2.dropdown;
  2587. } else {
  2588. if (methodsMap[method]) method = methodsMap[method];
  2589. value = select2[method].apply(select2, args.slice(1));
  2590. }
  2591. if (indexOf(args[0], valueMethods) >= 0
  2592. || (indexOf(args[0], propertyMethods) && args.length == 1)) {
  2593. return false; // abort the iteration, ready to return first matched value
  2594. }
  2595. } else {
  2596. throw "Invalid arguments to select2 plugin: " + args;
  2597. }
  2598. });
  2599. return (value === undefined) ? this : value;
  2600. };
  2601. // plugin defaults, accessible to users
  2602. $.fn.select2.defaults = {
  2603. width: "copy",
  2604. loadMorePadding: 0,
  2605. closeOnSelect: true,
  2606. openOnEnter: true,
  2607. containerCss: {},
  2608. dropdownCss: {},
  2609. containerCssClass: "",
  2610. dropdownCssClass: "",
  2611. formatResult: function(result, container, query, escapeMarkup) {
  2612. var markup=[];
  2613. markMatch(result.text, query.term, markup, escapeMarkup);
  2614. return markup.join("");
  2615. },
  2616. formatSelection: function (data, container, escapeMarkup) {
  2617. return data ? escapeMarkup(data.text) : undefined;
  2618. },
  2619. sortResults: function (results, container, query) {
  2620. return results;
  2621. },
  2622. formatResultCssClass: function(data) {return undefined;},
  2623. formatSelectionCssClass: function(data, container) {return undefined;},
  2624. formatNoMatches: function () { return "No matches found"; },
  2625. formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); },
  2626. formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
  2627. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
  2628. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  2629. formatSearching: function () { return "Searching..."; },
  2630. minimumResultsForSearch: 0,
  2631. minimumInputLength: 0,
  2632. maximumInputLength: null,
  2633. maximumSelectionSize: 0,
  2634. id: function (e) { return e.id; },
  2635. matcher: function(term, text) {
  2636. return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
  2637. },
  2638. separator: ",",
  2639. tokenSeparators: [],
  2640. tokenizer: defaultTokenizer,
  2641. escapeMarkup: defaultEscapeMarkup,
  2642. blurOnChange: false,
  2643. selectOnBlur: false,
  2644. adaptContainerCssClass: function(c) { return c; },
  2645. adaptDropdownCssClass: function(c) { return null; }
  2646. };
  2647. $.fn.select2.ajaxDefaults = {
  2648. transport: $.ajax,
  2649. params: {
  2650. type: "GET",
  2651. cache: false,
  2652. dataType: "json"
  2653. }
  2654. };
  2655. // exports
  2656. window.Select2 = {
  2657. query: {
  2658. ajax: ajax,
  2659. local: local,
  2660. tags: tags
  2661. }, util: {
  2662. debounce: debounce,
  2663. markMatch: markMatch,
  2664. escapeMarkup: defaultEscapeMarkup,
  2665. stripDiacritics: stripDiacritics
  2666. }, "class": {
  2667. "abstract": AbstractSelect2,
  2668. "single": SingleSelect2,
  2669. "multi": MultiSelect2
  2670. }
  2671. };
  2672. }(jQuery));