select2.js 118 KB

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