select2.js 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181
  1. /*
  2. Copyright 2012 Igor Vaynberg
  3. Version: @@ver@@ Timestamp: @@timestamp@@
  4. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in
  5. compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software distributed under the License is
  8. distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and limitations under the License.
  10. */
  11. (function ($) {
  12. if(typeof $.fn.each2 == "undefined"){
  13. $.fn.extend({
  14. /*
  15. * 4-10 times faster .each replacement
  16. * use it carefully, as it overrides jQuery context of element on each iteration
  17. */
  18. each2 : function (c) {
  19. var j = $([0]), i = -1, l = this.length;
  20. while (
  21. ++i < l
  22. && (j.context = j[0] = this[i])
  23. && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
  24. );
  25. return this;
  26. }
  27. });
  28. }
  29. })(jQuery);
  30. (function ($, undefined) {
  31. "use strict";
  32. /*global document, window, jQuery, console */
  33. if (window.Select2 !== undefined) {
  34. return;
  35. }
  36. var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer;
  37. KEY = {
  38. TAB: 9,
  39. ENTER: 13,
  40. ESC: 27,
  41. SPACE: 32,
  42. LEFT: 37,
  43. UP: 38,
  44. RIGHT: 39,
  45. DOWN: 40,
  46. SHIFT: 16,
  47. CTRL: 17,
  48. ALT: 18,
  49. PAGE_UP: 33,
  50. PAGE_DOWN: 34,
  51. HOME: 36,
  52. END: 35,
  53. BACKSPACE: 8,
  54. DELETE: 46,
  55. isArrow: function (k) {
  56. k = k.which ? k.which : k;
  57. switch (k) {
  58. case KEY.LEFT:
  59. case KEY.RIGHT:
  60. case KEY.UP:
  61. case KEY.DOWN:
  62. return true;
  63. }
  64. return false;
  65. },
  66. isControl: function (k) {
  67. k = k.which ? k.which : k;
  68. switch (k) {
  69. case KEY.SHIFT:
  70. case KEY.CTRL:
  71. case KEY.ALT:
  72. return true;
  73. }
  74. if (k.metaKey) return true;
  75. return false;
  76. },
  77. isFunctionKey: function (k) {
  78. k = k.which ? k.which : k;
  79. return k >= 112 && k <= 123;
  80. }
  81. };
  82. nextUid=(function() { var counter=1; return function() { return counter++; }; }());
  83. function escapeMarkup(markup) {
  84. if (markup && typeof(markup) === "string") {
  85. return markup.replace("&", "&amp;");
  86. } else {
  87. return markup;
  88. }
  89. }
  90. function indexOf(value, array) {
  91. var i = 0, l = array.length, v;
  92. if (typeof value === "undefined") {
  93. return -1;
  94. }
  95. if (value.constructor === String) {
  96. for (; i < l; i = i + 1) if (value.localeCompare(array[i]) === 0) return i;
  97. } else {
  98. for (; i < l; i = i + 1) {
  99. v = array[i];
  100. if (v.constructor === String) {
  101. if (v.localeCompare(value) === 0) return i;
  102. } else {
  103. if (v === value) return i;
  104. }
  105. }
  106. }
  107. return -1;
  108. }
  109. /**
  110. * Compares equality of a and b taking into account that a and b may be strings, in which case localeCompare is used
  111. * @param a
  112. * @param b
  113. */
  114. function equal(a, b) {
  115. if (a === b) return true;
  116. if (a === undefined || b === undefined) return false;
  117. if (a === null || b === null) return false;
  118. if (a.constructor === String) return a.localeCompare(b) === 0;
  119. if (b.constructor === String) return b.localeCompare(a) === 0;
  120. return false;
  121. }
  122. /**
  123. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  124. * strings
  125. * @param string
  126. * @param separator
  127. */
  128. function splitVal(string, separator) {
  129. var val, i, l;
  130. if (string === null || string.length < 1) return [];
  131. val = string.split(separator);
  132. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  133. return val;
  134. }
  135. function getSideBorderPadding(element) {
  136. return element.outerWidth() - element.width();
  137. }
  138. function installKeyUpChangeEvent(element) {
  139. var key="keyup-change-value";
  140. element.bind("keydown", function () {
  141. if ($.data(element, key) === undefined) {
  142. $.data(element, key, element.val());
  143. }
  144. });
  145. element.bind("keyup", function () {
  146. var val= $.data(element, key);
  147. if (val !== undefined && element.val() !== val) {
  148. $.removeData(element, key);
  149. element.trigger("keyup-change");
  150. }
  151. });
  152. }
  153. $(document).delegate("*", "mousemove", function (e) {
  154. $.data(document, "select2-lastpos", {x: e.pageX, y: e.pageY});
  155. });
  156. /**
  157. * filters mouse events so an event is fired only if the mouse moved.
  158. *
  159. * filters out mouse events that occur when mouse is stationary but
  160. * the elements under the pointer are scrolled.
  161. */
  162. function installFilteredMouseMove(element) {
  163. element.bind("mousemove", function (e) {
  164. var lastpos = $.data(document, "select2-lastpos");
  165. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  166. $(e.target).trigger("mousemove-filtered", e);
  167. }
  168. });
  169. }
  170. /**
  171. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  172. * within the last quietMillis milliseconds.
  173. *
  174. * @param quietMillis number of milliseconds to wait before invoking fn
  175. * @param fn function to be debounced
  176. * @return debounced version of fn
  177. */
  178. function debounce(quietMillis, fn) {
  179. var timeout;
  180. return function () {
  181. window.clearTimeout(timeout);
  182. timeout = window.setTimeout(fn, quietMillis);
  183. };
  184. }
  185. /**
  186. * A simple implementation of a thunk
  187. * @param formula function used to lazily initialize the thunk
  188. * @return {Function}
  189. */
  190. function thunk(formula) {
  191. var evaluated = false,
  192. value;
  193. return function() {
  194. if (evaluated === false) { value = formula(); evaluated = true; }
  195. return value;
  196. };
  197. };
  198. function installDebouncedScroll(threshold, element) {
  199. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  200. element.bind("scroll", function (e) {
  201. if (indexOf(e.target, element.get()) >= 0) notify(e);
  202. });
  203. }
  204. function killEvent(event) {
  205. event.preventDefault();
  206. event.stopPropagation();
  207. }
  208. function measureTextWidth(e) {
  209. if (!sizer){
  210. var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
  211. sizer = $("<div></div>").css({
  212. position: "absolute",
  213. left: "-10000px",
  214. top: "-10000px",
  215. display: "none",
  216. fontSize: style.fontSize,
  217. fontFamily: style.fontFamily,
  218. fontStyle: style.fontStyle,
  219. fontWeight: style.fontWeight,
  220. letterSpacing: style.letterSpacing,
  221. textTransform: style.textTransform,
  222. whiteSpace: "nowrap"
  223. });
  224. $("body").append(sizer);
  225. }
  226. sizer.text(e.val());
  227. return sizer.width();
  228. }
  229. function markMatch(text, term, markup) {
  230. var match=text.toUpperCase().indexOf(term.toUpperCase()),
  231. tl=term.length;
  232. if (match<0) {
  233. markup.push(text);
  234. return;
  235. }
  236. markup.push(text.substring(0, match));
  237. markup.push("<span class='select2-match'>");
  238. markup.push(text.substring(match, match + tl));
  239. markup.push("</span>");
  240. markup.push(text.substring(match + tl, text.length));
  241. }
  242. /**
  243. * Produces an ajax-based query function
  244. *
  245. * @param options object containing configuration paramters
  246. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  247. * @param options.url url for the data
  248. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  249. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
  250. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  251. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  252. * The expected format is an object containing the following keys:
  253. * results array of objects that will be used as choices
  254. * more (optional) boolean indicating whether there are more results available
  255. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  256. */
  257. function ajax(options) {
  258. var timeout, // current scheduled but not yet executed request
  259. requestSequence = 0, // sequence used to drop out-of-order responses
  260. handler = null,
  261. quietMillis = options.quietMillis || 100;
  262. return function (query) {
  263. window.clearTimeout(timeout);
  264. timeout = window.setTimeout(function () {
  265. requestSequence += 1; // increment the sequence
  266. var requestNumber = requestSequence, // this request's sequence number
  267. data = options.data, // ajax data function
  268. transport = options.transport || $.ajax,
  269. type = options.type || 'GET'; // set type of request (GET or POST)
  270. data = data.call(this, query.term, query.page, query.context);
  271. if( null !== handler) { handler.abort(); }
  272. handler = transport.call(null, {
  273. url: options.url,
  274. dataType: options.dataType,
  275. data: data,
  276. type: type,
  277. success: function (data) {
  278. if (requestNumber < requestSequence) {
  279. return;
  280. }
  281. // TODO 3.0 - replace query.page with query so users have access to term, page, etc.
  282. var results = options.results(data, query.page);
  283. query.callback(results);
  284. }
  285. });
  286. }, quietMillis);
  287. };
  288. }
  289. /**
  290. * Produces a query function that works with a local array
  291. *
  292. * @param options object containing configuration parameters. The options parameter can either be an array or an
  293. * object.
  294. *
  295. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  296. *
  297. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  298. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  299. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  300. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  301. * the text.
  302. */
  303. function local(options) {
  304. var data = options, // data elements
  305. dataText,
  306. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  307. if (!$.isArray(data)) {
  308. text = data.text;
  309. // if text is not a function we assume it to be a key name
  310. if (!$.isFunction(text)) {
  311. 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
  312. text = function (item) { return item[dataText]; };
  313. }
  314. data = data.results;
  315. }
  316. return function (query) {
  317. var t = query.term, filtered = {};
  318. if (t === "") {
  319. query.callback({results: data});
  320. return;
  321. }
  322. filtered.results = $(data)
  323. .filter(function () {return query.matcher(t, text(this));})
  324. .get();
  325. query.callback(filtered);
  326. };
  327. }
  328. // TODO javadoc
  329. function tags(data) {
  330. // TODO even for a function we should probably return a wrapper that does the same object/string check as
  331. // the function for arrays. otherwise only functions that return objects are supported.
  332. if ($.isFunction(data)) {
  333. return data;
  334. }
  335. // if not a function we assume it to be an array
  336. return function (query) {
  337. var t = query.term, filtered = {results: []};
  338. $(data).each(function () {
  339. var isObject = this.text !== undefined,
  340. text = isObject ? this.text : this;
  341. if (t === "" || query.matcher(t, text)) {
  342. filtered.results.push(isObject ? this : {id: this, text: this});
  343. }
  344. });
  345. query.callback(filtered);
  346. };
  347. }
  348. /**
  349. * blurs any Select2 container that has focus when an element outside them was clicked or received focus
  350. *
  351. * also takes care of clicks on label tags that point to the source element
  352. */
  353. $(document).ready(function () {
  354. $(document).delegate("*", "mousedown touchend", function (e) {
  355. var target = $(e.target).closest("div.select2-container").get(0), attr;
  356. if (target) {
  357. $(document).find("div.select2-container-active").each(function () {
  358. if (this !== target) $(this).data("select2").blur();
  359. });
  360. } else {
  361. target = $(e.target).closest("div.select2-drop").get(0);
  362. $(document).find("div.select2-drop-active").each(function () {
  363. if (this !== target) $(this).data("select2").blur();
  364. });
  365. }
  366. target=$(e.target);
  367. attr = target.attr("for");
  368. if ("LABEL" === e.target.tagName && attr && attr.length > 0) {
  369. target = $("#"+attr);
  370. target = target.data("select2");
  371. if (target !== undefined) { target.focus(); e.preventDefault();}
  372. }
  373. });
  374. });
  375. function evaluate(val) {
  376. return $.isFunction(val) ? val() : val;
  377. }
  378. /**
  379. * Creates a new class
  380. *
  381. * @param superClass
  382. * @param methods
  383. */
  384. function clazz(SuperClass, methods) {
  385. var constructor = function () {};
  386. constructor.prototype = new SuperClass;
  387. constructor.prototype.constructor = constructor;
  388. constructor.prototype.parent = SuperClass.prototype;
  389. constructor.prototype = $.extend(constructor.prototype, methods);
  390. return constructor;
  391. }
  392. AbstractSelect2 = clazz(Object, {
  393. // abstract
  394. bind: function (func) {
  395. var self = this;
  396. return function () {
  397. func.apply(self, arguments);
  398. };
  399. },
  400. // abstract
  401. init: function (opts) {
  402. var results, search, resultsSelector = ".select2-results";
  403. // prepare options
  404. this.opts = opts = this.prepareOpts(opts);
  405. this.id=opts.id;
  406. // destroy if called on an existing component
  407. if (opts.element.data("select2") !== undefined &&
  408. opts.element.data("select2") !== null) {
  409. this.destroy();
  410. }
  411. this.enabled=true;
  412. this.container = this.createContainer();
  413. // cache the body so future lookups are cheap
  414. this.body = thunk(function() { return opts.element.closest("body"); });
  415. if (opts.element.attr("class") !== undefined) {
  416. this.container.addClass(opts.element.attr("class"));
  417. }
  418. this.container.css(evaluate(opts.containerCss));
  419. this.container.addClass(evaluate(opts.containerCssClass));
  420. // swap container for the element
  421. this.opts.element
  422. .data("select2", this)
  423. .hide()
  424. .after(this.container);
  425. this.container.data("select2", this);
  426. this.dropdown = this.container.find(".select2-drop");
  427. this.dropdown.css(evaluate(opts.dropdownCss));
  428. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  429. this.dropdown.data("select2", this);
  430. this.results = results = this.container.find(resultsSelector);
  431. this.search = search = this.container.find("input.select2-input");
  432. search.attr("tabIndex", this.opts.element.attr("tabIndex"));
  433. this.resultsPage = 0;
  434. this.context = null;
  435. // initialize the container
  436. this.initContainer();
  437. this.initContainerWidth();
  438. installFilteredMouseMove(this.results);
  439. this.dropdown.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
  440. installDebouncedScroll(80, this.results);
  441. this.dropdown.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  442. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  443. if ($.fn.mousewheel) {
  444. results.mousewheel(function (e, delta, deltaX, deltaY) {
  445. var top = results.scrollTop(), height;
  446. if (deltaY > 0 && top - deltaY <= 0) {
  447. results.scrollTop(0);
  448. killEvent(e);
  449. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  450. results.scrollTop(results.get(0).scrollHeight - results.height());
  451. killEvent(e);
  452. }
  453. });
  454. }
  455. installKeyUpChangeEvent(search);
  456. search.bind("keyup-change", this.bind(this.updateResults));
  457. search.bind("focus", function () { search.addClass("select2-focused"); if (search.val() === " ") search.val(""); });
  458. search.bind("blur", function () { search.removeClass("select2-focused");});
  459. this.dropdown.delegate(resultsSelector, "mouseup", this.bind(function (e) {
  460. if ($(e.target).closest(".select2-result-selectable:not(.select2-disabled)").length > 0) {
  461. this.highlightUnderEvent(e);
  462. this.selectHighlighted(e);
  463. } else {
  464. this.focusSearch();
  465. }
  466. killEvent(e);
  467. }));
  468. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  469. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  470. // dom it will trigger the popup close, which is not what we want
  471. this.dropdown.bind("click mouseup mousedown", function (e) { e.stopPropagation(); });
  472. if ($.isFunction(this.opts.initSelection)) {
  473. // initialize selection based on the current value of the source element
  474. this.initSelection();
  475. // if the user has provided a function that can set selection based on the value of the source element
  476. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  477. this.monitorSource();
  478. }
  479. if (opts.element.is(":disabled")) this.disable();
  480. },
  481. // abstract
  482. destroy: function () {
  483. var select2 = this.opts.element.data("select2");
  484. if (select2 !== undefined) {
  485. select2.container.remove();
  486. select2.dropdown.remove();
  487. select2.opts.element
  488. .removeData("select2")
  489. .unbind(".select2")
  490. .show();
  491. }
  492. },
  493. // abstract
  494. prepareOpts: function (opts) {
  495. var element, select, idKey, ajaxUrl;
  496. element = opts.element;
  497. if (element.get(0).tagName.toLowerCase() === "select") {
  498. this.select = select = opts.element;
  499. }
  500. //Custom tags separator.
  501. opts.separator = opts.separator || ",";
  502. if (select) {
  503. // these options are not allowed when attached to a select because they are picked up off the element itself
  504. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  505. if (this in opts) {
  506. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  507. }
  508. });
  509. }
  510. opts = $.extend({}, {
  511. populateResults: function(container, results, query) {
  512. var populate, data, result, children, id=this.opts.id;
  513. populate=function(results, container, depth) {
  514. var i, l, result, selectable, compound, node, label, innerContainer, formatted;
  515. for (i = 0, l = results.length; i < l; i = i + 1) {
  516. result=results[i];
  517. selectable=id(result) !== undefined;
  518. compound=("children" in result) && result.children.length > 0;
  519. node=$("<li></li>");
  520. node.addClass("select2-results-dept-"+depth);
  521. node.addClass("select2-result");
  522. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  523. if (compound) { node.addClass("select2-result-with-children"); }
  524. label=$("<div></div>");
  525. label.addClass("select2-result-label");
  526. formatted=opts.formatResult(result, label, query);
  527. if (formatted!==undefined) {
  528. label.html(escapeMarkup(formatted));
  529. }
  530. node.append(label);
  531. if (compound) {
  532. innerContainer=$("<ul></ul>");
  533. innerContainer.addClass("select2-result-sub");
  534. populate(result.children, innerContainer, depth+1);
  535. node.append(innerContainer);
  536. }
  537. node.data("select2-data", result);
  538. container.append(node);
  539. }
  540. };
  541. populate(results, container, 0);
  542. }
  543. }, $.fn.select2.defaults, opts);
  544. if (typeof(opts.id) !== "function") {
  545. idKey = opts.id;
  546. opts.id = function (e) { return e[idKey]; };
  547. }
  548. if (select) {
  549. opts.query = this.bind(function (query) {
  550. var data = { results: [], more: false },
  551. term = query.term,
  552. children, firstChild, process;
  553. process=function(element, collection) {
  554. var group;
  555. if (element.is("option")) {
  556. if (query.matcher(term, element.text(), element)) {
  557. collection.push({id:element.attr("value"), text:element.text(), element: element.get()});
  558. }
  559. } else if (element.is("optgroup")) {
  560. group={text:element.attr("label"), children:[], element: element.get()};
  561. element.children().each2(function(i, elm) { process(elm, group.children); });
  562. if (group.children.length>0) {
  563. collection.push(group);
  564. }
  565. }
  566. };
  567. children=element.children();
  568. // ignore the placeholder option if there is one
  569. if (this.getPlaceholder() !== undefined && children.length > 0) {
  570. firstChild = children[0];
  571. if ($(firstChild).text() === "") {
  572. children=children.not(firstChild);
  573. }
  574. }
  575. children.each2(function(i, elm) { process(elm, data.results); });
  576. query.callback(data);
  577. });
  578. // this is needed because inside val() we construct choices from options and there id is hardcoded
  579. opts.id=function(e) { return e.id; };
  580. } else {
  581. if (!("query" in opts)) {
  582. if ("ajax" in opts) {
  583. ajaxUrl = opts.element.data("ajax-url");
  584. if (ajaxUrl && ajaxUrl.length > 0) {
  585. opts.ajax.url = ajaxUrl;
  586. }
  587. opts.query = ajax(opts.ajax);
  588. } else if ("data" in opts) {
  589. opts.query = local(opts.data);
  590. } else if ("tags" in opts) {
  591. opts.query = tags(opts.tags);
  592. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  593. opts.initSelection = function (element, callback) {
  594. var data = [];
  595. $(splitVal(element.val(), opts.separator)).each(function () {
  596. var id = this, text = this, tags=opts.tags;
  597. if ($.isFunction(tags)) tags=tags();
  598. $(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } });
  599. data.push({id: id, text: text});
  600. });
  601. callback(data);
  602. };
  603. }
  604. }
  605. }
  606. if (typeof(opts.query) !== "function") {
  607. throw "query function not defined for Select2 " + opts.element.attr("id");
  608. }
  609. return opts;
  610. },
  611. /**
  612. * Monitor the original element for changes and update select2 accordingly
  613. */
  614. // abstract
  615. monitorSource: function () {
  616. this.opts.element.bind("change.select2", this.bind(function (e) {
  617. if (this.opts.element.data("select2-change-triggered") !== true) {
  618. this.initSelection();
  619. }
  620. }));
  621. },
  622. /**
  623. * Triggers the change event on the source element
  624. */
  625. // abstract
  626. triggerChange: function (details) {
  627. details = details || {};
  628. details= $.extend({}, details, { type: "change", val: this.val() });
  629. // prevents recursive triggering
  630. this.opts.element.data("select2-change-triggered", true);
  631. this.opts.element.trigger(details);
  632. this.opts.element.data("select2-change-triggered", false);
  633. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  634. // so here we trigger the click event manually
  635. this.opts.element.click();
  636. },
  637. // abstract
  638. enable: function() {
  639. if (this.enabled) return;
  640. this.enabled=true;
  641. this.container.removeClass("select2-container-disabled");
  642. },
  643. // abstract
  644. disable: function() {
  645. if (!this.enabled) return;
  646. this.close();
  647. this.enabled=false;
  648. this.container.addClass("select2-container-disabled");
  649. },
  650. // abstract
  651. opened: function () {
  652. return this.container.hasClass("select2-dropdown-open");
  653. },
  654. // abstract
  655. positionDropdown: function() {
  656. var offset = this.container.offset(),
  657. height = this.container.outerHeight(),
  658. width = this.container.outerWidth(),
  659. dropHeight = this.dropdown.outerHeight(),
  660. viewportBottom = $(window).scrollTop() + document.documentElement.clientHeight,
  661. dropTop = offset.top + height,
  662. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  663. enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
  664. aboveNow = this.dropdown.hasClass("select2-drop-above"),
  665. above,
  666. css;
  667. // console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  668. // console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  669. // always prefer the current above/below alignment, unless there is not enough room
  670. if (aboveNow) {
  671. above = true;
  672. if (!enoughRoomAbove && enoughRoomBelow) above = false;
  673. } else {
  674. above = false;
  675. if (!enoughRoomBelow && enoughRoomAbove) above = true;
  676. }
  677. if (above) {
  678. dropTop = offset.top - dropHeight;
  679. this.container.addClass("select2-drop-above");
  680. this.dropdown.addClass("select2-drop-above");
  681. }
  682. else {
  683. this.container.removeClass("select2-drop-above");
  684. this.dropdown.removeClass("select2-drop-above");
  685. }
  686. css = {
  687. top:dropTop,
  688. left:offset.left,
  689. width:width
  690. };
  691. this.dropdown.css(css);
  692. },
  693. // abstract
  694. shouldOpen: function() {
  695. var event;
  696. if (this.opened()) return false;
  697. event = jQuery.Event("open");
  698. this.opts.element.trigger(event);
  699. return !event.isDefaultPrevented();
  700. },
  701. // abstract
  702. clearDropdownAlignmentPreference: function() {
  703. // clear the classes used to figure out the preference of where the dropdown should be opened
  704. this.container.removeClass("select2-drop-above");
  705. this.dropdown.removeClass("select2-drop-above");
  706. },
  707. /**
  708. * Opens the dropdown
  709. *
  710. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  711. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  712. */
  713. // abstract
  714. open: function () {
  715. if (!this.shouldOpen()) return false;
  716. window.setTimeout(this.bind(this.opening), 1);
  717. return true;
  718. },
  719. /**
  720. * Performs the opening of the dropdown
  721. */
  722. // abstract
  723. opening: function() {
  724. this.clearDropdownAlignmentPreference();
  725. if (this.search.val() === " ") { this.search.val(""); }
  726. this.dropdown.addClass("select2-drop-active");
  727. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  728. this.updateResults(true);
  729. if(this.dropdown[0] !== this.body().children().last()[0]) {
  730. this.dropdown.detach().appendTo(this.body());
  731. }
  732. this.dropdown.show();
  733. this.ensureHighlightVisible();
  734. this.positionDropdown();
  735. this.focusSearch();
  736. },
  737. // abstract
  738. close: function () {
  739. if (!this.opened()) return;
  740. this.clearDropdownAlignmentPreference();
  741. this.dropdown.hide();
  742. this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
  743. this.results.empty();
  744. this.clearSearch();
  745. this.opts.element.trigger(jQuery.Event("close"));
  746. },
  747. // abstract
  748. clearSearch: function () {
  749. },
  750. // abstract
  751. ensureHighlightVisible: function () {
  752. var results = this.results, children, index, child, hb, rb, y, more;
  753. index = this.highlight();
  754. if (index < 0) return;
  755. if (index == 0) {
  756. // if the first element is highlighted scroll all the way to the top,
  757. // that way any unselectable headers above it will also be scrolled
  758. // into view
  759. results.scrollTop(0);
  760. return;
  761. }
  762. children = results.find(".select2-result-selectable");
  763. child = $(children[index]);
  764. hb = child.offset().top + child.outerHeight();
  765. // if this is the last child lets also make sure select2-more-results is visible
  766. if (index === children.length - 1) {
  767. more = results.find("li.select2-more-results");
  768. if (more.length > 0) {
  769. hb = more.offset().top + more.outerHeight();
  770. }
  771. }
  772. rb = results.offset().top + results.outerHeight();
  773. if (hb > rb) {
  774. results.scrollTop(results.scrollTop() + (hb - rb));
  775. }
  776. y = child.offset().top - results.offset().top;
  777. // make sure the top of the element is visible
  778. if (y < 0) {
  779. results.scrollTop(results.scrollTop() + y); // y is negative
  780. }
  781. },
  782. // abstract
  783. moveHighlight: function (delta) {
  784. var choices = this.results.find(".select2-result-selectable"),
  785. index = this.highlight();
  786. while (index > -1 && index < choices.length) {
  787. index += delta;
  788. var choice = $(choices[index]);
  789. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled")) {
  790. this.highlight(index);
  791. break;
  792. }
  793. }
  794. },
  795. // abstract
  796. highlight: function (index) {
  797. var choices = this.results.find(".select2-result-selectable").not(".select2-disabled");
  798. if (arguments.length === 0) {
  799. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  800. }
  801. if (index >= choices.length) index = choices.length - 1;
  802. if (index < 0) index = 0;
  803. choices.removeClass("select2-highlighted");
  804. $(choices[index]).addClass("select2-highlighted");
  805. this.ensureHighlightVisible();
  806. },
  807. // abstract
  808. countSelectableResults: function() {
  809. return this.results.find(".select2-result-selectable").not(".select2-disabled").length;
  810. },
  811. // abstract
  812. highlightUnderEvent: function (event) {
  813. var el = $(event.target).closest(".select2-result-selectable");
  814. if (el.length > 0 && !el.is(".select2-highlighted")) {
  815. var choices = this.results.find('.select2-result-selectable');
  816. this.highlight(choices.index(el));
  817. } else if (el.length == 0) {
  818. // if we are over an unselectable item remove al highlights
  819. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  820. }
  821. },
  822. // abstract
  823. loadMoreIfNeeded: function () {
  824. var results = this.results,
  825. more = results.find("li.select2-more-results"),
  826. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  827. offset = -1, // index of first element without data
  828. page = this.resultsPage + 1,
  829. self=this,
  830. term=this.search.val(),
  831. context=this.context;
  832. if (more.length === 0) return;
  833. below = more.offset().top - results.offset().top - results.height();
  834. if (below <= 0) {
  835. more.addClass("select2-active");
  836. this.opts.query({
  837. term: term,
  838. page: page,
  839. context: context,
  840. matcher: this.opts.matcher,
  841. callback: this.bind(function (data) {
  842. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  843. if (data.more===true) {
  844. more.detach().appendTo(results.children(":last")).text(self.opts.formatLoadMore(page+1));
  845. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  846. } else {
  847. more.remove();
  848. }
  849. self.positionDropdown();
  850. self.resultsPage = page;
  851. })});
  852. }
  853. },
  854. /**
  855. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  856. */
  857. // abstract
  858. updateResults: function (initial) {
  859. var search = this.search, results = this.results, opts = this.opts, data, self=this;
  860. // if the search is currently hidden we do not alter the results
  861. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  862. return;
  863. }
  864. search.addClass("select2-active");
  865. function postRender() {
  866. results.scrollTop(0);
  867. search.removeClass("select2-active");
  868. self.positionDropdown();
  869. }
  870. function render(html) {
  871. results.html(escapeMarkup(html));
  872. postRender();
  873. }
  874. if (opts.maximumSelectionSize >=1) {
  875. data = this.data();
  876. if ($.isArray(data) && data.length >= opts.maximumSelectionSize) {
  877. render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(opts.maximumSelectionSize) + "</li>");
  878. return;
  879. }
  880. }
  881. if (search.val().length < opts.minimumInputLength) {
  882. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  883. return;
  884. }
  885. this.resultsPage = 1;
  886. opts.query({
  887. term: search.val(),
  888. page: this.resultsPage,
  889. context: null,
  890. matcher: opts.matcher,
  891. callback: this.bind(function (data) {
  892. var def; // default choice
  893. // save context, if any
  894. this.context = (data.context===undefined) ? null : data.context;
  895. // create a default choice and prepend it to the list
  896. if (this.opts.createSearchChoice && search.val() !== "") {
  897. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  898. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  899. if ($(data.results).filter(
  900. function () {
  901. return equal(self.id(this), self.id(def));
  902. }).length === 0) {
  903. data.results.unshift(def);
  904. }
  905. }
  906. }
  907. if (data.results.length === 0) {
  908. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  909. return;
  910. }
  911. results.empty();
  912. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  913. if (data.more === true) {
  914. results.children().filter(":last").append("<li class='select2-more-results'>" + escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
  915. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  916. }
  917. this.postprocessResults(data, initial);
  918. postRender();
  919. })});
  920. },
  921. // abstract
  922. cancel: function () {
  923. this.close();
  924. },
  925. // abstract
  926. blur: function () {
  927. this.close();
  928. this.container.removeClass("select2-container-active");
  929. this.dropdown.removeClass("select2-drop-active");
  930. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  931. if (this.search[0] === document.activeElement) { this.search.blur(); }
  932. this.clearSearch();
  933. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  934. },
  935. // abstract
  936. focusSearch: function () {
  937. /* we do this in a timeout so that current event processing can complete before this code is executed.
  938. this makes sure the search field is focussed even if the current event would blur it */
  939. window.setTimeout(this.bind(function () {
  940. this.search.focus();
  941. // reset the value so IE places the cursor at the end of the input box
  942. this.search.val(this.search.val());
  943. }), 10);
  944. },
  945. // abstract
  946. selectHighlighted: function () {
  947. var index=this.highlight(),
  948. highlighted=this.results.find(".select2-highlighted").not(".select2-disabled"),
  949. data = highlighted.closest('.select2-result-selectable').data("select2-data");
  950. if (data) {
  951. highlighted.addClass("select2-disabled");
  952. this.highlight(index);
  953. this.onSelect(data);
  954. }
  955. },
  956. // abstract
  957. getPlaceholder: function () {
  958. return this.opts.element.attr("placeholder") ||
  959. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  960. this.opts.element.data("placeholder") ||
  961. this.opts.placeholder;
  962. },
  963. /**
  964. * Get the desired width for the container element. This is
  965. * derived first from option `width` passed to select2, then
  966. * the inline 'style' on the original element, and finally
  967. * falls back to the jQuery calculated element width.
  968. */
  969. // abstract
  970. initContainerWidth: function () {
  971. function resolveContainerWidth() {
  972. var style, attrs, matches, i, l;
  973. if (this.opts.width === "off") {
  974. return null;
  975. } else if (this.opts.width === "element"){
  976. return this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px';
  977. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  978. // check if there is inline style on the element that contains width
  979. style = this.opts.element.attr('style');
  980. if (style !== undefined) {
  981. attrs = style.split(';');
  982. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  983. matches = attrs[i].replace(/\s/g, '')
  984. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  985. if (matches !== null && matches.length >= 1)
  986. return matches[1];
  987. }
  988. }
  989. if (this.opts.width === "resolve") {
  990. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  991. // when attached to input type=hidden or elements hidden via css
  992. style = this.opts.element.css('width');
  993. if (style.indexOf("%") > 0) return style;
  994. // finally, fallback on the calculated width of the element
  995. return (this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px');
  996. }
  997. return null;
  998. } else if ($.isFunction(this.opts.width)) {
  999. return this.opts.width();
  1000. } else {
  1001. return this.opts.width;
  1002. }
  1003. };
  1004. var width = resolveContainerWidth.call(this);
  1005. if (width !== null) {
  1006. this.container.attr("style", "width: "+width);
  1007. }
  1008. }
  1009. });
  1010. SingleSelect2 = clazz(AbstractSelect2, {
  1011. // single
  1012. createContainer: function () {
  1013. var container = $("<div></div>", {
  1014. "class": "select2-container"
  1015. }).html([
  1016. " <a href='javascript:void(0)' class='select2-choice'>",
  1017. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  1018. " <div><b></b></div>" ,
  1019. "</a>",
  1020. " <div class='select2-drop select2-offscreen'>" ,
  1021. " <div class='select2-search'>" ,
  1022. " <input type='text' autocomplete='off' class='select2-input'/>" ,
  1023. " </div>" ,
  1024. " <ul class='select2-results'>" ,
  1025. " </ul>" ,
  1026. "</div>"].join(""));
  1027. return container;
  1028. },
  1029. // single
  1030. opening: function () {
  1031. this.search.show();
  1032. this.parent.opening.apply(this, arguments);
  1033. this.dropdown.removeClass("select2-offscreen");
  1034. },
  1035. // single
  1036. close: function () {
  1037. if (!this.opened()) return;
  1038. this.parent.close.apply(this, arguments);
  1039. this.dropdown.removeAttr("style").addClass("select2-offscreen").insertAfter(this.selection).show();
  1040. },
  1041. // single
  1042. focus: function () {
  1043. this.close();
  1044. this.selection.focus();
  1045. },
  1046. // single
  1047. isFocused: function () {
  1048. return this.selection[0] === document.activeElement;
  1049. },
  1050. // single
  1051. cancel: function () {
  1052. this.parent.cancel.apply(this, arguments);
  1053. this.selection.focus();
  1054. },
  1055. // single
  1056. initContainer: function () {
  1057. var selection,
  1058. container = this.container,
  1059. dropdown = this.dropdown,
  1060. clickingInside = false;
  1061. this.selection = selection = container.find(".select2-choice");
  1062. this.search.bind("keydown", this.bind(function (e) {
  1063. if (!this.enabled) return;
  1064. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1065. // prevent the page from scrolling
  1066. killEvent(e);
  1067. return;
  1068. }
  1069. if (this.opened()) {
  1070. switch (e.which) {
  1071. case KEY.UP:
  1072. case KEY.DOWN:
  1073. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1074. killEvent(e);
  1075. return;
  1076. case KEY.TAB:
  1077. case KEY.ENTER:
  1078. this.selectHighlighted();
  1079. killEvent(e);
  1080. return;
  1081. case KEY.ESC:
  1082. this.cancel(e);
  1083. killEvent(e);
  1084. return;
  1085. }
  1086. } else {
  1087. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1088. return;
  1089. }
  1090. this.open();
  1091. if (e.which === KEY.ENTER) {
  1092. // do not propagate the event otherwise we open, and propagate enter which closes
  1093. return;
  1094. }
  1095. }
  1096. }));
  1097. this.search.bind("focus", this.bind(function() {
  1098. this.selection.attr("tabIndex", "-1");
  1099. }));
  1100. this.search.bind("blur", this.bind(function() {
  1101. if (!this.opened()) this.container.removeClass("select2-container-active");
  1102. window.setTimeout(this.bind(function() { this.selection.attr("tabIndex", this.opts.element.attr("tabIndex")); }), 10);
  1103. }));
  1104. selection.bind("mousedown", this.bind(function (e) {
  1105. clickingInside = true;
  1106. if (this.opened()) {
  1107. this.close();
  1108. this.selection.focus();
  1109. } else if (this.enabled) {
  1110. this.open();
  1111. }
  1112. killEvent(e);
  1113. clickingInside = false;
  1114. }));
  1115. dropdown.bind("mousedown", this.bind(function() { this.search.focus(); }));
  1116. selection.bind("focus", this.bind(function() {
  1117. this.container.addClass("select2-container-active");
  1118. // hide the search so the tab key does not focus on it
  1119. this.search.attr("tabIndex", "-1");
  1120. }));
  1121. selection.bind("blur", this.bind(function() {
  1122. this.container.removeClass("select2-container-active");
  1123. window.setTimeout(this.bind(function() { this.search.attr("tabIndex", this.opts.element.attr("tabIndex")); }), 10);
  1124. }));
  1125. selection.bind("keydown", this.bind(function(e) {
  1126. if (!this.enabled) return;
  1127. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1128. // prevent the page from scrolling
  1129. killEvent(e);
  1130. return;
  1131. }
  1132. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1133. return;
  1134. }
  1135. this.open();
  1136. if (e.which === KEY.ENTER) {
  1137. // do not propagate the event otherwise we open, and propagate enter which closes
  1138. killEvent(e);
  1139. return;
  1140. }
  1141. // do not set the search input value for non-alpha-numeric keys
  1142. // otherwise pressing down results in a '(' being set in the search field
  1143. if (e.which < 48 ) { // '0' == 48
  1144. killEvent(e);
  1145. return;
  1146. }
  1147. var keyWritten = String.fromCharCode(e.which).toLowerCase();
  1148. if (e.shiftKey) {
  1149. keyWritten = keyWritten.toUpperCase();
  1150. }
  1151. this.search.val(keyWritten);
  1152. // prevent event propagation so it doesnt replay on the now focussed search field and result in double key entry
  1153. killEvent(e);
  1154. }));
  1155. selection.delegate("abbr", "mousedown", this.bind(function (e) {
  1156. if (!this.enabled) return;
  1157. this.clear();
  1158. killEvent(e);
  1159. this.close();
  1160. this.triggerChange();
  1161. this.selection.focus();
  1162. }));
  1163. this.setPlaceholder();
  1164. this.search.bind("focus", this.bind(function() {
  1165. this.container.addClass("select2-container-active");
  1166. }));
  1167. },
  1168. // single
  1169. clear: function() {
  1170. this.opts.element.val("");
  1171. this.selection.find("span").empty();
  1172. this.selection.removeData("select2-data");
  1173. this.setPlaceholder();
  1174. },
  1175. /**
  1176. * Sets selection based on source element's value
  1177. */
  1178. // single
  1179. initSelection: function () {
  1180. var selected;
  1181. if (this.opts.element.val() === "") {
  1182. this.close();
  1183. this.setPlaceholder();
  1184. } else {
  1185. var self = this;
  1186. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1187. if (selected !== undefined && selected !== null) {
  1188. self.updateSelection(selected);
  1189. self.close();
  1190. self.setPlaceholder();
  1191. }
  1192. });
  1193. }
  1194. },
  1195. // single
  1196. prepareOpts: function () {
  1197. var opts = this.parent.prepareOpts.apply(this, arguments);
  1198. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1199. // install the selection initializer
  1200. opts.initSelection = function (element, callback) {
  1201. var selected = element.find(":selected");
  1202. // a single select box always has a value, no need to null check 'selected'
  1203. if ($.isFunction(callback))
  1204. callback({id: selected.attr("value"), text: selected.text()});
  1205. };
  1206. }
  1207. return opts;
  1208. },
  1209. // single
  1210. setPlaceholder: function () {
  1211. var placeholder = this.getPlaceholder();
  1212. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1213. // check for a first blank option if attached to a select
  1214. if (this.select && this.select.find("option:first").text() !== "") return;
  1215. this.selection.find("span").html(escapeMarkup(placeholder));
  1216. this.selection.addClass("select2-default");
  1217. this.selection.find("abbr").hide();
  1218. }
  1219. },
  1220. // single
  1221. postprocessResults: function (data, initial) {
  1222. var selected = 0, self = this, showSearchInput = true;
  1223. // find the selected element in the result list
  1224. this.results.find(".select2-result-selectable").each2(function (i, elm) {
  1225. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1226. selected = i;
  1227. return false;
  1228. }
  1229. });
  1230. // and highlight it
  1231. this.highlight(selected);
  1232. // hide the search box if this is the first we got the results and there are a few of them
  1233. if (initial === true) {
  1234. // TODO below we use data.results.length, but what we really need is something recursive to calc the length
  1235. // TODO in case there are optgroups
  1236. showSearchInput = this.showSearchInput = data.results.length >= this.opts.minimumResultsForSearch;
  1237. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1238. //add "select2-with-searchbox" to the container if search box is shown
  1239. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1240. }
  1241. },
  1242. // single
  1243. onSelect: function (data) {
  1244. var old = this.opts.element.val();
  1245. this.opts.element.val(this.id(data));
  1246. this.updateSelection(data);
  1247. this.close();
  1248. this.selection.focus();
  1249. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1250. },
  1251. // single
  1252. updateSelection: function (data) {
  1253. var container=this.selection.find("span"), formatted;
  1254. this.selection.data("select2-data", data);
  1255. container.empty();
  1256. formatted=this.opts.formatSelection(data, container);
  1257. if (formatted !== undefined) {
  1258. container.append(escapeMarkup(formatted));
  1259. }
  1260. this.selection.removeClass("select2-default");
  1261. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1262. this.selection.find("abbr").show();
  1263. }
  1264. },
  1265. // single
  1266. val: function () {
  1267. var val, data = null, self = this;
  1268. if (arguments.length === 0) {
  1269. return this.opts.element.val();
  1270. }
  1271. val = arguments[0];
  1272. if (this.select) {
  1273. this.select
  1274. .val(val)
  1275. .find(":selected").each2(function (i, elm) {
  1276. data = {id: elm.attr("value"), text: elm.text()};
  1277. return false;
  1278. });
  1279. this.updateSelection(data);
  1280. this.setPlaceholder();
  1281. } else {
  1282. if (this.opts.initSelection === undefined) {
  1283. throw new Error("cannot call val() if initSelection() is not defined");
  1284. }
  1285. // val is an id. !val is true for [undefined,null,'']
  1286. if (!val) {
  1287. this.clear();
  1288. return;
  1289. }
  1290. this.opts.initSelection(this.opts.element, function(data){
  1291. self.opts.element.val(!data ? "" : self.id(data));
  1292. self.updateSelection(data);
  1293. self.setPlaceholder();
  1294. });
  1295. }
  1296. },
  1297. // single
  1298. clearSearch: function () {
  1299. this.search.val("");
  1300. },
  1301. // single
  1302. data: function(value) {
  1303. var data;
  1304. if (arguments.length === 0) {
  1305. data = this.selection.data("select2-data");
  1306. if (data == undefined) data = null;
  1307. return data;
  1308. } else {
  1309. if (!value || value === "") {
  1310. this.clear();
  1311. } else {
  1312. this.opts.element.val(!value ? "" : this.id(value));
  1313. this.updateSelection(value);
  1314. }
  1315. }
  1316. }
  1317. });
  1318. MultiSelect2 = clazz(AbstractSelect2, {
  1319. // multi
  1320. createContainer: function () {
  1321. var container = $("<div></div>", {
  1322. "class": "select2-container select2-container-multi"
  1323. }).html([
  1324. " <ul class='select2-choices'>",
  1325. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1326. " <li class='select2-search-field'>" ,
  1327. " <input type='text' autocomplete='off' style='width: 25px;' class='select2-input'>" ,
  1328. " </li>" ,
  1329. "</ul>" ,
  1330. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1331. " <ul class='select2-results'>" ,
  1332. " </ul>" ,
  1333. "</div>"].join(""));
  1334. return container;
  1335. },
  1336. // multi
  1337. prepareOpts: function () {
  1338. var opts = this.parent.prepareOpts.apply(this, arguments);
  1339. // TODO validate placeholder is a string if specified
  1340. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1341. // install sthe selection initializer
  1342. opts.initSelection = function (element,callback) {
  1343. var data = [];
  1344. element.find(":selected").each2(function (i, elm) {
  1345. data.push({id: elm.attr("value"), text: elm.text()});
  1346. });
  1347. if ($.isFunction(callback))
  1348. callback(data);
  1349. };
  1350. }
  1351. return opts;
  1352. },
  1353. // multi
  1354. initContainer: function () {
  1355. var selector = ".select2-choices", selection;
  1356. this.searchContainer = this.container.find(".select2-search-field");
  1357. this.selection = selection = this.container.find(selector);
  1358. this.search.bind("keydown", this.bind(function (e) {
  1359. if (!this.enabled) return;
  1360. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1361. this.close();
  1362. var choices,
  1363. selected = selection.find(".select2-search-choice-focus");
  1364. if (selected.length > 0) {
  1365. this.unselect(selected.first());
  1366. this.search.width(10);
  1367. killEvent(e);
  1368. return;
  1369. }
  1370. choices = selection.find(".select2-search-choice");
  1371. if (choices.length > 0) {
  1372. choices.last().addClass("select2-search-choice-focus");
  1373. }
  1374. } else {
  1375. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1376. }
  1377. if (this.opened()) {
  1378. switch (e.which) {
  1379. case KEY.UP:
  1380. case KEY.DOWN:
  1381. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1382. killEvent(e);
  1383. return;
  1384. case KEY.ENTER:
  1385. case KEY.TAB:
  1386. this.selectHighlighted();
  1387. killEvent(e);
  1388. return;
  1389. case KEY.ESC:
  1390. this.cancel(e);
  1391. killEvent(e);
  1392. return;
  1393. }
  1394. }
  1395. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1396. return;
  1397. }
  1398. this.open();
  1399. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1400. // prevent the page from scrolling
  1401. killEvent(e);
  1402. }
  1403. }));
  1404. this.search.bind("keyup", this.bind(this.resizeSearch));
  1405. this.search.bind("blur", this.bind(function() {
  1406. this.container.removeClass("select2-container-active");
  1407. }));
  1408. this.container.delegate(selector, "mousedown", this.bind(function (e) {
  1409. if (!this.enabled) return;
  1410. this.clearPlaceholder();
  1411. this.open();
  1412. this.focusSearch();
  1413. e.preventDefault();
  1414. }));
  1415. this.container.delegate(selector, "focus", this.bind(function () {
  1416. if (!this.enabled) return;
  1417. this.container.addClass("select2-container-active");
  1418. this.dropdown.addClass("select2-drop-active");
  1419. this.clearPlaceholder();
  1420. }));
  1421. // set the placeholder if necessary
  1422. this.clearSearch();
  1423. },
  1424. // multi
  1425. enable: function() {
  1426. if (this.enabled) return;
  1427. this.parent.enable.apply(this, arguments);
  1428. this.search.removeAttr("disabled");
  1429. },
  1430. // multi
  1431. disable: function() {
  1432. if (!this.enabled) return;
  1433. this.parent.disable.apply(this, arguments);
  1434. this.search.attr("disabled", true);
  1435. },
  1436. // multi
  1437. initSelection: function () {
  1438. var data;
  1439. if (this.opts.element.val() === "") {
  1440. this.updateSelection([]);
  1441. this.close();
  1442. // set the placeholder if necessary
  1443. this.clearSearch();
  1444. }
  1445. if (this.select || this.opts.element.val() !== "") {
  1446. var self = this;
  1447. this.opts.initSelection.call(null, this.opts.element, function(data){
  1448. if (data !== undefined && data !== null) {
  1449. self.updateSelection(data);
  1450. self.close();
  1451. // set the placeholder if necessary
  1452. self.clearSearch();
  1453. }
  1454. });
  1455. }
  1456. },
  1457. // multi
  1458. clearSearch: function () {
  1459. var placeholder = this.getPlaceholder();
  1460. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1461. this.search.val(placeholder).addClass("select2-default");
  1462. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1463. this.resizeSearch();
  1464. } else {
  1465. // we set this to " " instead of "" and later clear it on focus() because there is a firefox bug
  1466. // that does not properly render the caret when the field starts out blank
  1467. this.search.val(" ").width(10);
  1468. }
  1469. },
  1470. // multi
  1471. clearPlaceholder: function () {
  1472. if (this.search.hasClass("select2-default")) {
  1473. this.search.val("").removeClass("select2-default");
  1474. } else {
  1475. // work around for the space character we set to avoid firefox caret bug
  1476. if (this.search.val() === " ") this.search.val("");
  1477. }
  1478. },
  1479. // multi
  1480. opening: function () {
  1481. this.parent.opening.apply(this, arguments);
  1482. this.clearPlaceholder();
  1483. this.resizeSearch();
  1484. this.focusSearch();
  1485. },
  1486. // multi
  1487. close: function () {
  1488. if (!this.opened()) return;
  1489. this.parent.close.apply(this, arguments);
  1490. },
  1491. // multi
  1492. focus: function () {
  1493. this.close();
  1494. this.search.focus();
  1495. },
  1496. // multi
  1497. isFocused: function () {
  1498. return this.search.hasClass("select2-focused");
  1499. },
  1500. // multi
  1501. updateSelection: function (data) {
  1502. var ids = [], filtered = [], self = this;
  1503. // filter out duplicates
  1504. $(data).each(function () {
  1505. if (indexOf(self.id(this), ids) < 0) {
  1506. ids.push(self.id(this));
  1507. filtered.push(this);
  1508. }
  1509. });
  1510. data = filtered;
  1511. this.selection.find(".select2-search-choice").remove();
  1512. $(data).each(function () {
  1513. self.addSelectedChoice(this);
  1514. });
  1515. self.postprocessResults();
  1516. },
  1517. // multi
  1518. onSelect: function (data) {
  1519. this.addSelectedChoice(data);
  1520. if (this.select) { this.postprocessResults(); }
  1521. if (this.opts.closeOnSelect) {
  1522. this.close();
  1523. this.search.width(10);
  1524. } else {
  1525. this.search.width(10);
  1526. this.resizeSearch();
  1527. if (this.countSelectableResults()>0) {
  1528. this.positionDropdown();
  1529. } else {
  1530. // if nothing left to select close
  1531. this.close();
  1532. }
  1533. }
  1534. // since its not possible to select an element that has already been
  1535. // added we do not need to check if this is a new element before firing change
  1536. this.triggerChange({ added: data });
  1537. this.focusSearch();
  1538. },
  1539. // multi
  1540. cancel: function () {
  1541. this.close();
  1542. this.focusSearch();
  1543. },
  1544. // multi
  1545. addSelectedChoice: function (data) {
  1546. var choice=$(
  1547. "<li class='select2-search-choice'>" +
  1548. " <div></div>" +
  1549. " <a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>" +
  1550. "</li>"),
  1551. id = this.id(data),
  1552. val = this.getVal(),
  1553. formatted;
  1554. formatted=this.opts.formatSelection(data, choice);
  1555. choice.find("div").replaceWith("<div>"+escapeMarkup(formatted)+"</div>");
  1556. choice.find(".select2-search-choice-close")
  1557. .bind("click dblclick", this.bind(function (e) {
  1558. if (!this.enabled) return;
  1559. $(e.target).closest(".select2-search-choice").fadeOut('fast').animate({width: "hide"}, 50, this.bind(function(){
  1560. this.unselect($(e.target));
  1561. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1562. this.close();
  1563. this.focusSearch();
  1564. })).dequeue();
  1565. killEvent(e);
  1566. })).bind("focus", this.bind(function () {
  1567. if (!this.enabled) return;
  1568. this.container.addClass("select2-container-active");
  1569. this.dropdown.addClass("select2-drop-active");
  1570. }));
  1571. choice.data("select2-data", data);
  1572. choice.insertBefore(this.searchContainer);
  1573. val.push(id);
  1574. this.setVal(val);
  1575. },
  1576. // multi
  1577. unselect: function (selected) {
  1578. var val = this.getVal(),
  1579. data,
  1580. index;
  1581. selected = selected.closest(".select2-search-choice");
  1582. if (selected.length === 0) {
  1583. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1584. }
  1585. data = selected.data("select2-data");
  1586. index = indexOf(this.id(data), val);
  1587. if (index >= 0) {
  1588. val.splice(index, 1);
  1589. this.setVal(val);
  1590. if (this.select) this.postprocessResults();
  1591. }
  1592. selected.remove();
  1593. this.triggerChange({ removed: data });
  1594. },
  1595. // multi
  1596. postprocessResults: function () {
  1597. var val = this.getVal(),
  1598. choices = this.results.find(".select2-result-selectable"),
  1599. compound = this.results.find(".select2-result-with-children"),
  1600. self = this;
  1601. choices.each2(function (i, choice) {
  1602. var id = self.id(choice.data("select2-data"));
  1603. if (indexOf(id, val) >= 0) {
  1604. choice.addClass("select2-disabled").removeClass("select2-result-selectable");
  1605. } else {
  1606. choice.removeClass("select2-disabled").addClass("select2-result-selectable");
  1607. }
  1608. });
  1609. compound.each2(function(i, e) {
  1610. if (e.find(".select2-result-selectable").length==0) {
  1611. e.addClass("select2-disabled");
  1612. } else {
  1613. e.removeClass("select2-disabled");
  1614. }
  1615. });
  1616. choices.each2(function (i, choice) {
  1617. if (!choice.hasClass("select2-disabled") && choice.hasClass("select2-result-selectable")) {
  1618. self.highlight(0);
  1619. return false;
  1620. }
  1621. });
  1622. },
  1623. // multi
  1624. resizeSearch: function () {
  1625. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  1626. sideBorderPadding = getSideBorderPadding(this.search);
  1627. minimumWidth = measureTextWidth(this.search) + 10;
  1628. left = this.search.offset().left;
  1629. maxWidth = this.selection.width();
  1630. containerLeft = this.selection.offset().left;
  1631. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  1632. if (searchWidth < minimumWidth) {
  1633. searchWidth = maxWidth - sideBorderPadding;
  1634. }
  1635. if (searchWidth < 40) {
  1636. searchWidth = maxWidth - sideBorderPadding;
  1637. }
  1638. this.search.width(searchWidth);
  1639. },
  1640. // multi
  1641. getVal: function () {
  1642. var val;
  1643. if (this.select) {
  1644. val = this.select.val();
  1645. return val === null ? [] : val;
  1646. } else {
  1647. val = this.opts.element.val();
  1648. return splitVal(val, this.opts.separator);
  1649. }
  1650. },
  1651. // multi
  1652. setVal: function (val) {
  1653. var unique;
  1654. if (this.select) {
  1655. this.select.val(val);
  1656. } else {
  1657. unique = [];
  1658. // filter out duplicates
  1659. $(val).each(function () {
  1660. if (indexOf(this, unique) < 0) unique.push(this);
  1661. });
  1662. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  1663. }
  1664. },
  1665. // multi
  1666. val: function () {
  1667. var val, data = [], self=this;
  1668. if (arguments.length === 0) {
  1669. return this.getVal();
  1670. }
  1671. val = arguments[0];
  1672. if (!val) {
  1673. this.opts.element.val("");
  1674. this.updateSelection([]);
  1675. this.clearSearch();
  1676. return;
  1677. }
  1678. // val is a list of ids
  1679. this.setVal(val);
  1680. if (this.select) {
  1681. this.select.find(":selected").each(function () {
  1682. data.push({id: $(this).attr("value"), text: $(this).text()});
  1683. });
  1684. this.updateSelection(data);
  1685. } else {
  1686. if (this.opts.initSelection === undefined) {
  1687. throw new Error("val() cannot be called if initSelection() is not defined")
  1688. }
  1689. this.opts.initSelection(this.opts.element, function(data){
  1690. var ids=$(data).map(self.id);
  1691. self.setVal(ids);
  1692. self.updateSelection(data);
  1693. self.clearSearch();
  1694. });
  1695. }
  1696. this.clearSearch();
  1697. },
  1698. // multi
  1699. onSortStart: function() {
  1700. if (this.select) {
  1701. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  1702. }
  1703. // collapse search field into 0 width so its container can be collapsed as well
  1704. this.search.width(0);
  1705. // hide the container
  1706. this.searchContainer.hide();
  1707. },
  1708. // multi
  1709. onSortEnd:function() {
  1710. var val=[], self=this;
  1711. // show search and move it to the end of the list
  1712. this.searchContainer.show();
  1713. // make sure the search container is the last item in the list
  1714. this.searchContainer.appendTo(this.searchContainer.parent());
  1715. // since we collapsed the width in dragStarted, we resize it here
  1716. this.resizeSearch();
  1717. // update selection
  1718. this.selection.find(".select2-search-choice").each(function() {
  1719. val.push(self.opts.id($(this).data("select2-data")));
  1720. });
  1721. this.setVal(val);
  1722. this.triggerChange();
  1723. },
  1724. // multi
  1725. data: function(values) {
  1726. var self=this, ids;
  1727. if (arguments.length === 0) {
  1728. return this.selection
  1729. .find(".select2-search-choice")
  1730. .map(function() { return $(this).data("select2-data"); })
  1731. .get();
  1732. } else {
  1733. if (!values) { values = []; }
  1734. ids = $.map(values, function(e) { return self.opts.id(e)});
  1735. this.setVal(ids);
  1736. this.updateSelection(values);
  1737. this.clearSearch();
  1738. }
  1739. }
  1740. });
  1741. $.fn.select2 = function () {
  1742. var args = Array.prototype.slice.call(arguments, 0),
  1743. opts,
  1744. select2,
  1745. value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
  1746. this.each(function () {
  1747. if (args.length === 0 || typeof(args[0]) === "object") {
  1748. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1749. opts.element = $(this);
  1750. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1751. multiple = opts.element.attr("multiple");
  1752. } else {
  1753. multiple = opts.multiple || false;
  1754. if ("tags" in opts) {opts.multiple = multiple = true;}
  1755. }
  1756. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1757. select2.init(opts);
  1758. } else if (typeof(args[0]) === "string") {
  1759. if (indexOf(args[0], allowedMethods) < 0) {
  1760. throw "Unknown method: " + args[0];
  1761. }
  1762. value = undefined;
  1763. select2 = $(this).data("select2");
  1764. if (select2 === undefined) return;
  1765. if (args[0] === "container") {
  1766. value=select2.container;
  1767. } else {
  1768. value = select2[args[0]].apply(select2, args.slice(1));
  1769. }
  1770. if (value !== undefined) {return false;}
  1771. } else {
  1772. throw "Invalid arguments to select2 plugin: " + args;
  1773. }
  1774. });
  1775. return (value === undefined) ? this : value;
  1776. };
  1777. // plugin defaults, accessible to users
  1778. $.fn.select2.defaults = {
  1779. width: "copy",
  1780. closeOnSelect: true,
  1781. containerCss: {},
  1782. dropdownCss: {},
  1783. containerCssClass: "",
  1784. dropdownCssClass: "",
  1785. formatResult: function(result, container, query) {
  1786. var markup=[];
  1787. markMatch(result.text, query.term, markup);
  1788. return markup.join("");
  1789. },
  1790. formatSelection: function (data, container) {
  1791. return data.text;
  1792. },
  1793. formatNoMatches: function () { return "No matches found"; },
  1794. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  1795. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " items"; },
  1796. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  1797. minimumResultsForSearch: 0,
  1798. minimumInputLength: 0,
  1799. maximumSelectionSize: 0,
  1800. id: function (e) { return e.id; },
  1801. matcher: function(term, text) {
  1802. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  1803. }
  1804. };
  1805. // exports
  1806. window.Select2 = {
  1807. query: {
  1808. ajax: ajax,
  1809. local: local,
  1810. tags: tags
  1811. }, util: {
  1812. debounce: debounce,
  1813. markMatch: markMatch
  1814. }, "class": {
  1815. "abstract": AbstractSelect2,
  1816. "single": SingleSelect2,
  1817. "multi": MultiSelect2
  1818. }
  1819. };
  1820. }(jQuery));