select2.js 118 KB

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