select2.js 106 KB

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