select2.js 105 KB

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