select2.js 111 KB

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