select2.js 114 KB

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