select2.js 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197
  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(/&/g, "&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. * Checks if the formatter function should be used.
  350. *
  351. * Throws an error if it is not a function. Returns true if it should be used,
  352. * false if no formatting should be performed.
  353. *
  354. * @param formatter
  355. */
  356. function checkFormatter(formatter, formatterName) {
  357. if ($.isFunction(formatter)) return true;
  358. if (!formatter) return fasle;
  359. throw new Error("formatterName must be a function or a falsy value");
  360. }
  361. /**
  362. * blurs any Select2 container that has focus when an element outside them was clicked or received focus
  363. *
  364. * also takes care of clicks on label tags that point to the source element
  365. */
  366. $(document).ready(function () {
  367. $(document).delegate("*", "mousedown touchend", function (e) {
  368. var target = $(e.target).closest("div.select2-container").get(0), attr;
  369. if (target) {
  370. $(document).find("div.select2-container-active").each(function () {
  371. if (this !== target) $(this).data("select2").blur();
  372. });
  373. } else {
  374. target = $(e.target).closest("div.select2-drop").get(0);
  375. $(document).find("div.select2-drop-active").each(function () {
  376. if (this !== target) $(this).data("select2").blur();
  377. });
  378. }
  379. target=$(e.target);
  380. attr = target.attr("for");
  381. if ("LABEL" === e.target.tagName && attr && attr.length > 0) {
  382. target = $("#"+attr);
  383. target = target.data("select2");
  384. if (target !== undefined) { target.focus(); e.preventDefault();}
  385. }
  386. });
  387. });
  388. function evaluate(val) {
  389. return $.isFunction(val) ? val() : val;
  390. }
  391. /**
  392. * Creates a new class
  393. *
  394. * @param superClass
  395. * @param methods
  396. */
  397. function clazz(SuperClass, methods) {
  398. var constructor = function () {};
  399. constructor.prototype = new SuperClass;
  400. constructor.prototype.constructor = constructor;
  401. constructor.prototype.parent = SuperClass.prototype;
  402. constructor.prototype = $.extend(constructor.prototype, methods);
  403. return constructor;
  404. }
  405. AbstractSelect2 = clazz(Object, {
  406. // abstract
  407. bind: function (func) {
  408. var self = this;
  409. return function () {
  410. func.apply(self, arguments);
  411. };
  412. },
  413. // abstract
  414. init: function (opts) {
  415. var results, search, resultsSelector = ".select2-results";
  416. // prepare options
  417. this.opts = opts = this.prepareOpts(opts);
  418. this.id=opts.id;
  419. // destroy if called on an existing component
  420. if (opts.element.data("select2") !== undefined &&
  421. opts.element.data("select2") !== null) {
  422. this.destroy();
  423. }
  424. this.enabled=true;
  425. this.container = this.createContainer();
  426. // cache the body so future lookups are cheap
  427. this.body = thunk(function() { return opts.element.closest("body"); });
  428. if (opts.element.attr("class") !== undefined) {
  429. this.container.addClass(opts.element.attr("class"));
  430. }
  431. this.container.css(evaluate(opts.containerCss));
  432. this.container.addClass(evaluate(opts.containerCssClass));
  433. // swap container for the element
  434. this.opts.element
  435. .data("select2", this)
  436. .hide()
  437. .after(this.container);
  438. this.container.data("select2", this);
  439. this.dropdown = this.container.find(".select2-drop");
  440. this.dropdown.css(evaluate(opts.dropdownCss));
  441. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  442. this.dropdown.data("select2", this);
  443. this.results = results = this.container.find(resultsSelector);
  444. this.search = search = this.container.find("input.select2-input");
  445. search.attr("tabIndex", this.opts.element.attr("tabIndex"));
  446. this.resultsPage = 0;
  447. this.context = null;
  448. // initialize the container
  449. this.initContainer();
  450. this.initContainerWidth();
  451. installFilteredMouseMove(this.results);
  452. this.dropdown.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
  453. installDebouncedScroll(80, this.results);
  454. this.dropdown.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  455. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  456. if ($.fn.mousewheel) {
  457. results.mousewheel(function (e, delta, deltaX, deltaY) {
  458. var top = results.scrollTop(), height;
  459. if (deltaY > 0 && top - deltaY <= 0) {
  460. results.scrollTop(0);
  461. killEvent(e);
  462. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  463. results.scrollTop(results.get(0).scrollHeight - results.height());
  464. killEvent(e);
  465. }
  466. });
  467. }
  468. installKeyUpChangeEvent(search);
  469. search.bind("keyup-change", this.bind(this.updateResults));
  470. search.bind("focus", function () { search.addClass("select2-focused"); if (search.val() === " ") search.val(""); });
  471. search.bind("blur", function () { search.removeClass("select2-focused");});
  472. this.dropdown.delegate(resultsSelector, "mouseup", this.bind(function (e) {
  473. if ($(e.target).closest(".select2-result-selectable:not(.select2-disabled)").length > 0) {
  474. this.highlightUnderEvent(e);
  475. this.selectHighlighted(e);
  476. } else {
  477. this.focusSearch();
  478. }
  479. killEvent(e);
  480. }));
  481. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  482. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  483. // dom it will trigger the popup close, which is not what we want
  484. this.dropdown.bind("click mouseup mousedown", function (e) { e.stopPropagation(); });
  485. if ($.isFunction(this.opts.initSelection)) {
  486. // initialize selection based on the current value of the source element
  487. this.initSelection();
  488. // if the user has provided a function that can set selection based on the value of the source element
  489. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  490. this.monitorSource();
  491. }
  492. if (opts.element.is(":disabled")) this.disable();
  493. },
  494. // abstract
  495. destroy: function () {
  496. var select2 = this.opts.element.data("select2");
  497. if (select2 !== undefined) {
  498. select2.container.remove();
  499. select2.dropdown.remove();
  500. select2.opts.element
  501. .removeData("select2")
  502. .unbind(".select2")
  503. .show();
  504. }
  505. },
  506. // abstract
  507. prepareOpts: function (opts) {
  508. var element, select, idKey, ajaxUrl;
  509. element = opts.element;
  510. if (element.get(0).tagName.toLowerCase() === "select") {
  511. this.select = select = opts.element;
  512. }
  513. //Custom tags separator.
  514. opts.separator = opts.separator || ",";
  515. if (select) {
  516. // these options are not allowed when attached to a select because they are picked up off the element itself
  517. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  518. if (this in opts) {
  519. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  520. }
  521. });
  522. }
  523. opts = $.extend({}, {
  524. populateResults: function(container, results, query) {
  525. var populate, data, result, children, id=this.opts.id;
  526. populate=function(results, container, depth) {
  527. var i, l, result, selectable, compound, node, label, innerContainer, formatted;
  528. for (i = 0, l = results.length; i < l; i = i + 1) {
  529. result=results[i];
  530. selectable=id(result) !== undefined;
  531. compound=("children" in result) && result.children.length > 0;
  532. node=$("<li></li>");
  533. node.addClass("select2-results-dept-"+depth);
  534. node.addClass("select2-result");
  535. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  536. if (compound) { node.addClass("select2-result-with-children"); }
  537. label=$("<div></div>");
  538. label.addClass("select2-result-label");
  539. formatted=opts.formatResult(result, label, query);
  540. if (formatted!==undefined) {
  541. label.html(escapeMarkup(formatted));
  542. }
  543. node.append(label);
  544. if (compound) {
  545. innerContainer=$("<ul></ul>");
  546. innerContainer.addClass("select2-result-sub");
  547. populate(result.children, innerContainer, depth+1);
  548. node.append(innerContainer);
  549. }
  550. node.data("select2-data", result);
  551. container.append(node);
  552. }
  553. };
  554. populate(results, container, 0);
  555. }
  556. }, $.fn.select2.defaults, opts);
  557. if (typeof(opts.id) !== "function") {
  558. idKey = opts.id;
  559. opts.id = function (e) { return e[idKey]; };
  560. }
  561. if (select) {
  562. opts.query = this.bind(function (query) {
  563. var data = { results: [], more: false },
  564. term = query.term,
  565. children, firstChild, process;
  566. process=function(element, collection) {
  567. var group;
  568. if (element.is("option")) {
  569. if (query.matcher(term, element.text(), element)) {
  570. collection.push({id:element.attr("value"), text:element.text(), element: element.get()});
  571. }
  572. } else if (element.is("optgroup")) {
  573. group={text:element.attr("label"), children:[], element: element.get()};
  574. element.children().each2(function(i, elm) { process(elm, group.children); });
  575. if (group.children.length>0) {
  576. collection.push(group);
  577. }
  578. }
  579. };
  580. children=element.children();
  581. // ignore the placeholder option if there is one
  582. if (this.getPlaceholder() !== undefined && children.length > 0) {
  583. firstChild = children[0];
  584. if ($(firstChild).text() === "") {
  585. children=children.not(firstChild);
  586. }
  587. }
  588. children.each2(function(i, elm) { process(elm, data.results); });
  589. query.callback(data);
  590. });
  591. // this is needed because inside val() we construct choices from options and there id is hardcoded
  592. opts.id=function(e) { return e.id; };
  593. } else {
  594. if (!("query" in opts)) {
  595. if ("ajax" in opts) {
  596. ajaxUrl = opts.element.data("ajax-url");
  597. if (ajaxUrl && ajaxUrl.length > 0) {
  598. opts.ajax.url = ajaxUrl;
  599. }
  600. opts.query = ajax(opts.ajax);
  601. } else if ("data" in opts) {
  602. opts.query = local(opts.data);
  603. } else if ("tags" in opts) {
  604. opts.query = tags(opts.tags);
  605. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  606. opts.initSelection = function (element, callback) {
  607. var data = [];
  608. $(splitVal(element.val(), opts.separator)).each(function () {
  609. var id = this, text = this, tags=opts.tags;
  610. if ($.isFunction(tags)) tags=tags();
  611. $(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } });
  612. data.push({id: id, text: text});
  613. });
  614. callback(data);
  615. };
  616. }
  617. }
  618. }
  619. if (typeof(opts.query) !== "function") {
  620. throw "query function not defined for Select2 " + opts.element.attr("id");
  621. }
  622. return opts;
  623. },
  624. /**
  625. * Monitor the original element for changes and update select2 accordingly
  626. */
  627. // abstract
  628. monitorSource: function () {
  629. this.opts.element.bind("change.select2", this.bind(function (e) {
  630. if (this.opts.element.data("select2-change-triggered") !== true) {
  631. this.initSelection();
  632. }
  633. }));
  634. },
  635. /**
  636. * Triggers the change event on the source element
  637. */
  638. // abstract
  639. triggerChange: function (details) {
  640. details = details || {};
  641. details= $.extend({}, details, { type: "change", val: this.val() });
  642. // prevents recursive triggering
  643. this.opts.element.data("select2-change-triggered", true);
  644. this.opts.element.trigger(details);
  645. this.opts.element.data("select2-change-triggered", false);
  646. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  647. // so here we trigger the click event manually
  648. this.opts.element.click();
  649. },
  650. // abstract
  651. enable: function() {
  652. if (this.enabled) return;
  653. this.enabled=true;
  654. this.container.removeClass("select2-container-disabled");
  655. },
  656. // abstract
  657. disable: function() {
  658. if (!this.enabled) return;
  659. this.close();
  660. this.enabled=false;
  661. this.container.addClass("select2-container-disabled");
  662. },
  663. // abstract
  664. opened: function () {
  665. return this.container.hasClass("select2-dropdown-open");
  666. },
  667. // abstract
  668. positionDropdown: function() {
  669. var offset = this.container.offset(),
  670. height = this.container.outerHeight(),
  671. width = this.container.outerWidth(),
  672. dropHeight = this.dropdown.outerHeight(),
  673. viewportBottom = $(window).scrollTop() + document.documentElement.clientHeight,
  674. dropTop = offset.top + height,
  675. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  676. enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
  677. aboveNow = this.dropdown.hasClass("select2-drop-above"),
  678. above,
  679. css;
  680. // console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  681. // console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  682. // always prefer the current above/below alignment, unless there is not enough room
  683. if (aboveNow) {
  684. above = true;
  685. if (!enoughRoomAbove && enoughRoomBelow) above = false;
  686. } else {
  687. above = false;
  688. if (!enoughRoomBelow && enoughRoomAbove) above = true;
  689. }
  690. if (above) {
  691. dropTop = offset.top - dropHeight;
  692. this.container.addClass("select2-drop-above");
  693. this.dropdown.addClass("select2-drop-above");
  694. }
  695. else {
  696. this.container.removeClass("select2-drop-above");
  697. this.dropdown.removeClass("select2-drop-above");
  698. }
  699. css = {
  700. top:dropTop,
  701. left:offset.left,
  702. width:width
  703. };
  704. this.dropdown.css(css);
  705. },
  706. // abstract
  707. shouldOpen: function() {
  708. var event;
  709. if (this.opened()) return false;
  710. event = jQuery.Event("open");
  711. this.opts.element.trigger(event);
  712. return !event.isDefaultPrevented();
  713. },
  714. // abstract
  715. clearDropdownAlignmentPreference: function() {
  716. // clear the classes used to figure out the preference of where the dropdown should be opened
  717. this.container.removeClass("select2-drop-above");
  718. this.dropdown.removeClass("select2-drop-above");
  719. },
  720. /**
  721. * Opens the dropdown
  722. *
  723. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  724. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  725. */
  726. // abstract
  727. open: function () {
  728. if (!this.shouldOpen()) return false;
  729. window.setTimeout(this.bind(this.opening), 1);
  730. return true;
  731. },
  732. /**
  733. * Performs the opening of the dropdown
  734. */
  735. // abstract
  736. opening: function() {
  737. this.clearDropdownAlignmentPreference();
  738. if (this.search.val() === " ") { this.search.val(""); }
  739. this.dropdown.addClass("select2-drop-active");
  740. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  741. this.updateResults(true);
  742. if(this.dropdown[0] !== this.body().children().last()[0]) {
  743. this.dropdown.detach().appendTo(this.body());
  744. }
  745. this.dropdown.show();
  746. this.ensureHighlightVisible();
  747. this.positionDropdown();
  748. this.focusSearch();
  749. },
  750. // abstract
  751. close: function () {
  752. if (!this.opened()) return;
  753. this.clearDropdownAlignmentPreference();
  754. this.dropdown.hide();
  755. this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
  756. this.results.empty();
  757. this.clearSearch();
  758. this.opts.element.trigger(jQuery.Event("close"));
  759. },
  760. // abstract
  761. clearSearch: function () {
  762. },
  763. // abstract
  764. ensureHighlightVisible: function () {
  765. var results = this.results, children, index, child, hb, rb, y, more;
  766. index = this.highlight();
  767. if (index < 0) return;
  768. if (index == 0) {
  769. // if the first element is highlighted scroll all the way to the top,
  770. // that way any unselectable headers above it will also be scrolled
  771. // into view
  772. results.scrollTop(0);
  773. return;
  774. }
  775. children = results.find(".select2-result-selectable");
  776. child = $(children[index]);
  777. hb = child.offset().top + child.outerHeight();
  778. // if this is the last child lets also make sure select2-more-results is visible
  779. if (index === children.length - 1) {
  780. more = results.find("li.select2-more-results");
  781. if (more.length > 0) {
  782. hb = more.offset().top + more.outerHeight();
  783. }
  784. }
  785. rb = results.offset().top + results.outerHeight();
  786. if (hb > rb) {
  787. results.scrollTop(results.scrollTop() + (hb - rb));
  788. }
  789. y = child.offset().top - results.offset().top;
  790. // make sure the top of the element is visible
  791. if (y < 0) {
  792. results.scrollTop(results.scrollTop() + y); // y is negative
  793. }
  794. },
  795. // abstract
  796. moveHighlight: function (delta) {
  797. var choices = this.results.find(".select2-result-selectable"),
  798. index = this.highlight();
  799. while (index > -1 && index < choices.length) {
  800. index += delta;
  801. var choice = $(choices[index]);
  802. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled")) {
  803. this.highlight(index);
  804. break;
  805. }
  806. }
  807. },
  808. // abstract
  809. highlight: function (index) {
  810. var choices = this.results.find(".select2-result-selectable").not(".select2-disabled");
  811. if (arguments.length === 0) {
  812. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  813. }
  814. if (index >= choices.length) index = choices.length - 1;
  815. if (index < 0) index = 0;
  816. choices.removeClass("select2-highlighted");
  817. $(choices[index]).addClass("select2-highlighted");
  818. this.ensureHighlightVisible();
  819. },
  820. // abstract
  821. countSelectableResults: function() {
  822. return this.results.find(".select2-result-selectable").not(".select2-disabled").length;
  823. },
  824. // abstract
  825. highlightUnderEvent: function (event) {
  826. var el = $(event.target).closest(".select2-result-selectable");
  827. if (el.length > 0 && !el.is(".select2-highlighted")) {
  828. var choices = this.results.find('.select2-result-selectable');
  829. this.highlight(choices.index(el));
  830. } else if (el.length == 0) {
  831. // if we are over an unselectable item remove al highlights
  832. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  833. }
  834. },
  835. // abstract
  836. loadMoreIfNeeded: function () {
  837. var results = this.results,
  838. more = results.find("li.select2-more-results"),
  839. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  840. offset = -1, // index of first element without data
  841. page = this.resultsPage + 1,
  842. self=this,
  843. term=this.search.val(),
  844. context=this.context;
  845. if (more.length === 0) return;
  846. below = more.offset().top - results.offset().top - results.height();
  847. if (below <= 0) {
  848. more.addClass("select2-active");
  849. this.opts.query({
  850. term: term,
  851. page: page,
  852. context: context,
  853. matcher: this.opts.matcher,
  854. callback: this.bind(function (data) {
  855. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  856. if (data.more===true) {
  857. more.detach().appendTo(results.children(":last")).text(self.opts.formatLoadMore(page+1));
  858. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  859. } else {
  860. more.remove();
  861. }
  862. self.positionDropdown();
  863. self.resultsPage = page;
  864. })});
  865. }
  866. },
  867. /**
  868. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  869. */
  870. // abstract
  871. updateResults: function (initial) {
  872. var search = this.search, results = this.results, opts = this.opts, data, self=this;
  873. // if the search is currently hidden we do not alter the results
  874. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  875. return;
  876. }
  877. search.addClass("select2-active");
  878. function postRender() {
  879. results.scrollTop(0);
  880. search.removeClass("select2-active");
  881. self.positionDropdown();
  882. }
  883. function render(html) {
  884. results.html(escapeMarkup(html));
  885. postRender();
  886. }
  887. if (opts.maximumSelectionSize >=1) {
  888. data = this.data();
  889. if ($.isArray(data) && data.length >= opts.maximumSelectionSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  890. render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(opts.maximumSelectionSize) + "</li>");
  891. return;
  892. }
  893. }
  894. if (search.val().length < opts.minimumInputLength && checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  895. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  896. return;
  897. }
  898. this.resultsPage = 1;
  899. opts.query({
  900. term: search.val(),
  901. page: this.resultsPage,
  902. context: null,
  903. matcher: opts.matcher,
  904. callback: this.bind(function (data) {
  905. var def; // default choice
  906. // save context, if any
  907. this.context = (data.context===undefined) ? null : data.context;
  908. // create a default choice and prepend it to the list
  909. if (this.opts.createSearchChoice && search.val() !== "") {
  910. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  911. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  912. if ($(data.results).filter(
  913. function () {
  914. return equal(self.id(this), self.id(def));
  915. }).length === 0) {
  916. data.results.unshift(def);
  917. }
  918. }
  919. }
  920. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  921. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  922. return;
  923. }
  924. results.empty();
  925. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  926. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  927. results.children().filter(":last").append("<li class='select2-more-results'>" + escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
  928. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  929. }
  930. this.postprocessResults(data, initial);
  931. postRender();
  932. })});
  933. },
  934. // abstract
  935. cancel: function () {
  936. this.close();
  937. },
  938. // abstract
  939. blur: function () {
  940. this.close();
  941. this.container.removeClass("select2-container-active");
  942. this.dropdown.removeClass("select2-drop-active");
  943. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  944. if (this.search[0] === document.activeElement) { this.search.blur(); }
  945. this.clearSearch();
  946. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  947. },
  948. // abstract
  949. focusSearch: function () {
  950. /* we do this in a timeout so that current event processing can complete before this code is executed.
  951. this makes sure the search field is focussed even if the current event would blur it */
  952. window.setTimeout(this.bind(function () {
  953. this.search.focus();
  954. // reset the value so IE places the cursor at the end of the input box
  955. this.search.val(this.search.val());
  956. }), 10);
  957. },
  958. // abstract
  959. selectHighlighted: function () {
  960. var index=this.highlight(),
  961. highlighted=this.results.find(".select2-highlighted").not(".select2-disabled"),
  962. data = highlighted.closest('.select2-result-selectable').data("select2-data");
  963. if (data) {
  964. highlighted.addClass("select2-disabled");
  965. this.highlight(index);
  966. this.onSelect(data);
  967. }
  968. },
  969. // abstract
  970. getPlaceholder: function () {
  971. return this.opts.element.attr("placeholder") ||
  972. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  973. this.opts.element.data("placeholder") ||
  974. this.opts.placeholder;
  975. },
  976. /**
  977. * Get the desired width for the container element. This is
  978. * derived first from option `width` passed to select2, then
  979. * the inline 'style' on the original element, and finally
  980. * falls back to the jQuery calculated element width.
  981. */
  982. // abstract
  983. initContainerWidth: function () {
  984. function resolveContainerWidth() {
  985. var style, attrs, matches, i, l;
  986. if (this.opts.width === "off") {
  987. return null;
  988. } else if (this.opts.width === "element"){
  989. return this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px';
  990. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  991. // check if there is inline style on the element that contains width
  992. style = this.opts.element.attr('style');
  993. if (style !== undefined) {
  994. attrs = style.split(';');
  995. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  996. matches = attrs[i].replace(/\s/g, '')
  997. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  998. if (matches !== null && matches.length >= 1)
  999. return matches[1];
  1000. }
  1001. }
  1002. if (this.opts.width === "resolve") {
  1003. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1004. // when attached to input type=hidden or elements hidden via css
  1005. style = this.opts.element.css('width');
  1006. if (style.indexOf("%") > 0) return style;
  1007. // finally, fallback on the calculated width of the element
  1008. return (this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px');
  1009. }
  1010. return null;
  1011. } else if ($.isFunction(this.opts.width)) {
  1012. return this.opts.width();
  1013. } else {
  1014. return this.opts.width;
  1015. }
  1016. };
  1017. var width = resolveContainerWidth.call(this);
  1018. if (width !== null) {
  1019. this.container.attr("style", "width: "+width);
  1020. }
  1021. }
  1022. });
  1023. SingleSelect2 = clazz(AbstractSelect2, {
  1024. // single
  1025. createContainer: function () {
  1026. var container = $("<div></div>", {
  1027. "class": "select2-container"
  1028. }).html([
  1029. " <a href='javascript:void(0)' class='select2-choice'>",
  1030. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  1031. " <div><b></b></div>" ,
  1032. "</a>",
  1033. " <div class='select2-drop select2-offscreen'>" ,
  1034. " <div class='select2-search'>" ,
  1035. " <input type='text' autocomplete='off' class='select2-input'/>" ,
  1036. " </div>" ,
  1037. " <ul class='select2-results'>" ,
  1038. " </ul>" ,
  1039. "</div>"].join(""));
  1040. return container;
  1041. },
  1042. // single
  1043. opening: function () {
  1044. this.search.show();
  1045. this.parent.opening.apply(this, arguments);
  1046. this.dropdown.removeClass("select2-offscreen");
  1047. },
  1048. // single
  1049. close: function () {
  1050. if (!this.opened()) return;
  1051. this.parent.close.apply(this, arguments);
  1052. this.dropdown.removeAttr("style").addClass("select2-offscreen").insertAfter(this.selection).show();
  1053. },
  1054. // single
  1055. focus: function () {
  1056. this.close();
  1057. this.selection.focus();
  1058. },
  1059. // single
  1060. isFocused: function () {
  1061. return this.selection[0] === document.activeElement;
  1062. },
  1063. // single
  1064. cancel: function () {
  1065. this.parent.cancel.apply(this, arguments);
  1066. this.selection.focus();
  1067. },
  1068. // single
  1069. initContainer: function () {
  1070. var selection,
  1071. container = this.container,
  1072. dropdown = this.dropdown,
  1073. clickingInside = false;
  1074. this.selection = selection = container.find(".select2-choice");
  1075. this.search.bind("keydown", this.bind(function (e) {
  1076. if (!this.enabled) return;
  1077. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1078. // prevent the page from scrolling
  1079. killEvent(e);
  1080. return;
  1081. }
  1082. if (this.opened()) {
  1083. switch (e.which) {
  1084. case KEY.UP:
  1085. case KEY.DOWN:
  1086. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1087. killEvent(e);
  1088. return;
  1089. case KEY.TAB:
  1090. case KEY.ENTER:
  1091. this.selectHighlighted();
  1092. killEvent(e);
  1093. return;
  1094. case KEY.ESC:
  1095. this.cancel(e);
  1096. killEvent(e);
  1097. return;
  1098. }
  1099. } else {
  1100. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1101. return;
  1102. }
  1103. this.open();
  1104. if (e.which === KEY.ENTER) {
  1105. // do not propagate the event otherwise we open, and propagate enter which closes
  1106. return;
  1107. }
  1108. }
  1109. }));
  1110. this.search.bind("focus", this.bind(function() {
  1111. this.selection.attr("tabIndex", "-1");
  1112. }));
  1113. this.search.bind("blur", this.bind(function() {
  1114. if (!this.opened()) this.container.removeClass("select2-container-active");
  1115. window.setTimeout(this.bind(function() { this.selection.attr("tabIndex", this.opts.element.attr("tabIndex")); }), 10);
  1116. }));
  1117. selection.bind("mousedown", this.bind(function (e) {
  1118. clickingInside = true;
  1119. if (this.opened()) {
  1120. this.close();
  1121. this.selection.focus();
  1122. } else if (this.enabled) {
  1123. this.open();
  1124. }
  1125. clickingInside = false;
  1126. }));
  1127. dropdown.bind("mousedown", this.bind(function() { this.search.focus(); }));
  1128. selection.bind("focus", this.bind(function() {
  1129. this.container.addClass("select2-container-active");
  1130. // hide the search so the tab key does not focus on it
  1131. this.search.attr("tabIndex", "-1");
  1132. }));
  1133. selection.bind("blur", this.bind(function() {
  1134. if (!this.opened()) {
  1135. this.container.removeClass("select2-container-active");
  1136. }
  1137. window.setTimeout(this.bind(function() { this.search.attr("tabIndex", this.opts.element.attr("tabIndex")); }), 10);
  1138. }));
  1139. selection.bind("keydown", this.bind(function(e) {
  1140. if (!this.enabled) return;
  1141. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1142. // prevent the page from scrolling
  1143. killEvent(e);
  1144. return;
  1145. }
  1146. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1147. return;
  1148. }
  1149. this.open();
  1150. if (e.which === KEY.ENTER) {
  1151. // do not propagate the event otherwise we open, and propagate enter which closes
  1152. killEvent(e);
  1153. return;
  1154. }
  1155. // do not set the search input value for non-alpha-numeric keys
  1156. // otherwise pressing down results in a '(' being set in the search field
  1157. if (e.which < 48 ) { // '0' == 48
  1158. killEvent(e);
  1159. return;
  1160. }
  1161. var keyWritten = String.fromCharCode(e.which).toLowerCase();
  1162. if (e.shiftKey) {
  1163. keyWritten = keyWritten.toUpperCase();
  1164. }
  1165. this.search.val(keyWritten);
  1166. // prevent event propagation so it doesnt replay on the now focussed search field and result in double key entry
  1167. killEvent(e);
  1168. }));
  1169. selection.delegate("abbr", "mousedown", this.bind(function (e) {
  1170. if (!this.enabled) return;
  1171. this.clear();
  1172. killEvent(e);
  1173. this.close();
  1174. this.triggerChange();
  1175. this.selection.focus();
  1176. }));
  1177. this.setPlaceholder();
  1178. this.search.bind("focus", this.bind(function() {
  1179. this.container.addClass("select2-container-active");
  1180. }));
  1181. },
  1182. // single
  1183. clear: function() {
  1184. this.opts.element.val("");
  1185. this.selection.find("span").empty();
  1186. this.selection.removeData("select2-data");
  1187. this.setPlaceholder();
  1188. },
  1189. /**
  1190. * Sets selection based on source element's value
  1191. */
  1192. // single
  1193. initSelection: function () {
  1194. var selected;
  1195. if (this.opts.element.val() === "") {
  1196. this.close();
  1197. this.setPlaceholder();
  1198. } else {
  1199. var self = this;
  1200. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1201. if (selected !== undefined && selected !== null) {
  1202. self.updateSelection(selected);
  1203. self.close();
  1204. self.setPlaceholder();
  1205. }
  1206. });
  1207. }
  1208. },
  1209. // single
  1210. prepareOpts: function () {
  1211. var opts = this.parent.prepareOpts.apply(this, arguments);
  1212. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1213. // install the selection initializer
  1214. opts.initSelection = function (element, callback) {
  1215. var selected = element.find(":selected");
  1216. // a single select box always has a value, no need to null check 'selected'
  1217. if ($.isFunction(callback))
  1218. callback({id: selected.attr("value"), text: selected.text()});
  1219. };
  1220. }
  1221. return opts;
  1222. },
  1223. // single
  1224. setPlaceholder: function () {
  1225. var placeholder = this.getPlaceholder();
  1226. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1227. // check for a first blank option if attached to a select
  1228. if (this.select && this.select.find("option:first").text() !== "") return;
  1229. this.selection.find("span").html(escapeMarkup(placeholder));
  1230. this.selection.addClass("select2-default");
  1231. this.selection.find("abbr").hide();
  1232. }
  1233. },
  1234. // single
  1235. postprocessResults: function (data, initial) {
  1236. var selected = 0, self = this, showSearchInput = true;
  1237. // find the selected element in the result list
  1238. this.results.find(".select2-result-selectable").each2(function (i, elm) {
  1239. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1240. selected = i;
  1241. return false;
  1242. }
  1243. });
  1244. // and highlight it
  1245. this.highlight(selected);
  1246. // hide the search box if this is the first we got the results and there are a few of them
  1247. if (initial === true) {
  1248. // TODO below we use data.results.length, but what we really need is something recursive to calc the length
  1249. // TODO in case there are optgroups
  1250. showSearchInput = this.showSearchInput = data.results.length >= this.opts.minimumResultsForSearch;
  1251. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1252. //add "select2-with-searchbox" to the container if search box is shown
  1253. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1254. }
  1255. },
  1256. // single
  1257. onSelect: function (data) {
  1258. var old = this.opts.element.val();
  1259. this.opts.element.val(this.id(data));
  1260. this.updateSelection(data);
  1261. this.close();
  1262. this.selection.focus();
  1263. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1264. },
  1265. // single
  1266. updateSelection: function (data) {
  1267. var container=this.selection.find("span"), formatted;
  1268. this.selection.data("select2-data", data);
  1269. container.empty();
  1270. formatted=this.opts.formatSelection(data, container);
  1271. if (formatted !== undefined) {
  1272. container.append(escapeMarkup(formatted));
  1273. }
  1274. this.selection.removeClass("select2-default");
  1275. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1276. this.selection.find("abbr").show();
  1277. }
  1278. },
  1279. // single
  1280. val: function () {
  1281. var val, data = null, self = this;
  1282. if (arguments.length === 0) {
  1283. return this.opts.element.val();
  1284. }
  1285. val = arguments[0];
  1286. if (this.select) {
  1287. this.select
  1288. .val(val)
  1289. .find(":selected").each2(function (i, elm) {
  1290. data = {id: elm.attr("value"), text: elm.text()};
  1291. return false;
  1292. });
  1293. this.updateSelection(data);
  1294. this.setPlaceholder();
  1295. } else {
  1296. if (this.opts.initSelection === undefined) {
  1297. throw new Error("cannot call val() if initSelection() is not defined");
  1298. }
  1299. // val is an id. !val is true for [undefined,null,'']
  1300. if (!val) {
  1301. this.clear();
  1302. return;
  1303. }
  1304. this.opts.initSelection(this.opts.element, function(data){
  1305. self.opts.element.val(!data ? "" : self.id(data));
  1306. self.updateSelection(data);
  1307. self.setPlaceholder();
  1308. });
  1309. }
  1310. },
  1311. // single
  1312. clearSearch: function () {
  1313. this.search.val("");
  1314. },
  1315. // single
  1316. data: function(value) {
  1317. var data;
  1318. if (arguments.length === 0) {
  1319. data = this.selection.data("select2-data");
  1320. if (data == undefined) data = null;
  1321. return data;
  1322. } else {
  1323. if (!value || value === "") {
  1324. this.clear();
  1325. } else {
  1326. this.opts.element.val(!value ? "" : this.id(value));
  1327. this.updateSelection(value);
  1328. }
  1329. }
  1330. }
  1331. });
  1332. MultiSelect2 = clazz(AbstractSelect2, {
  1333. // multi
  1334. createContainer: function () {
  1335. var container = $("<div></div>", {
  1336. "class": "select2-container select2-container-multi"
  1337. }).html([
  1338. " <ul class='select2-choices'>",
  1339. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1340. " <li class='select2-search-field'>" ,
  1341. " <input type='text' autocomplete='off' style='width: 25px;' class='select2-input'>" ,
  1342. " </li>" ,
  1343. "</ul>" ,
  1344. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1345. " <ul class='select2-results'>" ,
  1346. " </ul>" ,
  1347. "</div>"].join(""));
  1348. return container;
  1349. },
  1350. // multi
  1351. prepareOpts: function () {
  1352. var opts = this.parent.prepareOpts.apply(this, arguments);
  1353. // TODO validate placeholder is a string if specified
  1354. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1355. // install sthe selection initializer
  1356. opts.initSelection = function (element,callback) {
  1357. var data = [];
  1358. element.find(":selected").each2(function (i, elm) {
  1359. data.push({id: elm.attr("value"), text: elm.text()});
  1360. });
  1361. if ($.isFunction(callback))
  1362. callback(data);
  1363. };
  1364. }
  1365. return opts;
  1366. },
  1367. // multi
  1368. initContainer: function () {
  1369. var selector = ".select2-choices", selection;
  1370. this.searchContainer = this.container.find(".select2-search-field");
  1371. this.selection = selection = this.container.find(selector);
  1372. this.search.bind("keydown", this.bind(function (e) {
  1373. if (!this.enabled) return;
  1374. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1375. this.close();
  1376. var choices,
  1377. selected = selection.find(".select2-search-choice-focus");
  1378. if (selected.length > 0) {
  1379. this.unselect(selected.first());
  1380. this.search.width(10);
  1381. killEvent(e);
  1382. return;
  1383. }
  1384. choices = selection.find(".select2-search-choice");
  1385. if (choices.length > 0) {
  1386. choices.last().addClass("select2-search-choice-focus");
  1387. }
  1388. } else {
  1389. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1390. }
  1391. if (this.opened()) {
  1392. switch (e.which) {
  1393. case KEY.UP:
  1394. case KEY.DOWN:
  1395. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1396. killEvent(e);
  1397. return;
  1398. case KEY.ENTER:
  1399. case KEY.TAB:
  1400. this.selectHighlighted();
  1401. killEvent(e);
  1402. return;
  1403. case KEY.ESC:
  1404. this.cancel(e);
  1405. killEvent(e);
  1406. return;
  1407. }
  1408. }
  1409. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1410. return;
  1411. }
  1412. this.open();
  1413. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1414. // prevent the page from scrolling
  1415. killEvent(e);
  1416. }
  1417. }));
  1418. this.search.bind("keyup", this.bind(this.resizeSearch));
  1419. this.search.bind("blur", this.bind(function() {
  1420. this.container.removeClass("select2-container-active");
  1421. }));
  1422. this.container.delegate(selector, "mousedown", this.bind(function (e) {
  1423. if (!this.enabled) return;
  1424. this.clearPlaceholder();
  1425. this.open();
  1426. this.focusSearch();
  1427. e.preventDefault();
  1428. }));
  1429. this.container.delegate(selector, "focus", this.bind(function () {
  1430. if (!this.enabled) return;
  1431. this.container.addClass("select2-container-active");
  1432. this.dropdown.addClass("select2-drop-active");
  1433. this.clearPlaceholder();
  1434. }));
  1435. // set the placeholder if necessary
  1436. this.clearSearch();
  1437. },
  1438. // multi
  1439. enable: function() {
  1440. if (this.enabled) return;
  1441. this.parent.enable.apply(this, arguments);
  1442. this.search.removeAttr("disabled");
  1443. },
  1444. // multi
  1445. disable: function() {
  1446. if (!this.enabled) return;
  1447. this.parent.disable.apply(this, arguments);
  1448. this.search.attr("disabled", true);
  1449. },
  1450. // multi
  1451. initSelection: function () {
  1452. var data;
  1453. if (this.opts.element.val() === "") {
  1454. this.updateSelection([]);
  1455. this.close();
  1456. // set the placeholder if necessary
  1457. this.clearSearch();
  1458. }
  1459. if (this.select || this.opts.element.val() !== "") {
  1460. var self = this;
  1461. this.opts.initSelection.call(null, this.opts.element, function(data){
  1462. if (data !== undefined && data !== null) {
  1463. self.updateSelection(data);
  1464. self.close();
  1465. // set the placeholder if necessary
  1466. self.clearSearch();
  1467. }
  1468. });
  1469. }
  1470. },
  1471. // multi
  1472. clearSearch: function () {
  1473. var placeholder = this.getPlaceholder();
  1474. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1475. this.search.val(placeholder).addClass("select2-default");
  1476. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1477. this.resizeSearch();
  1478. } else {
  1479. // we set this to " " instead of "" and later clear it on focus() because there is a firefox bug
  1480. // that does not properly render the caret when the field starts out blank
  1481. this.search.val(" ").width(10);
  1482. }
  1483. },
  1484. // multi
  1485. clearPlaceholder: function () {
  1486. if (this.search.hasClass("select2-default")) {
  1487. this.search.val("").removeClass("select2-default");
  1488. } else {
  1489. // work around for the space character we set to avoid firefox caret bug
  1490. if (this.search.val() === " ") this.search.val("");
  1491. }
  1492. },
  1493. // multi
  1494. opening: function () {
  1495. this.parent.opening.apply(this, arguments);
  1496. this.clearPlaceholder();
  1497. this.resizeSearch();
  1498. this.focusSearch();
  1499. },
  1500. // multi
  1501. close: function () {
  1502. if (!this.opened()) return;
  1503. this.parent.close.apply(this, arguments);
  1504. },
  1505. // multi
  1506. focus: function () {
  1507. this.close();
  1508. this.search.focus();
  1509. },
  1510. // multi
  1511. isFocused: function () {
  1512. return this.search.hasClass("select2-focused");
  1513. },
  1514. // multi
  1515. updateSelection: function (data) {
  1516. var ids = [], filtered = [], self = this;
  1517. // filter out duplicates
  1518. $(data).each(function () {
  1519. if (indexOf(self.id(this), ids) < 0) {
  1520. ids.push(self.id(this));
  1521. filtered.push(this);
  1522. }
  1523. });
  1524. data = filtered;
  1525. this.selection.find(".select2-search-choice").remove();
  1526. $(data).each(function () {
  1527. self.addSelectedChoice(this);
  1528. });
  1529. self.postprocessResults();
  1530. },
  1531. // multi
  1532. onSelect: function (data) {
  1533. this.addSelectedChoice(data);
  1534. if (this.select) { this.postprocessResults(); }
  1535. if (this.opts.closeOnSelect) {
  1536. this.close();
  1537. this.search.width(10);
  1538. } else {
  1539. this.search.width(10);
  1540. this.resizeSearch();
  1541. if (this.countSelectableResults()>0) {
  1542. this.positionDropdown();
  1543. } else {
  1544. // if nothing left to select close
  1545. this.close();
  1546. }
  1547. }
  1548. // since its not possible to select an element that has already been
  1549. // added we do not need to check if this is a new element before firing change
  1550. this.triggerChange({ added: data });
  1551. this.focusSearch();
  1552. },
  1553. // multi
  1554. cancel: function () {
  1555. this.close();
  1556. this.focusSearch();
  1557. },
  1558. // multi
  1559. addSelectedChoice: function (data) {
  1560. var choice=$(
  1561. "<li class='select2-search-choice'>" +
  1562. " <div></div>" +
  1563. " <a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>" +
  1564. "</li>"),
  1565. id = this.id(data),
  1566. val = this.getVal(),
  1567. formatted;
  1568. formatted=this.opts.formatSelection(data, choice);
  1569. choice.find("div").replaceWith("<div>"+escapeMarkup(formatted)+"</div>");
  1570. choice.find(".select2-search-choice-close")
  1571. .bind("mousedown", killEvent)
  1572. .bind("click dblclick", this.bind(function (e) {
  1573. if (!this.enabled) return;
  1574. $(e.target).closest(".select2-search-choice").fadeOut('fast').animate({width: "hide"}, 50, this.bind(function(){
  1575. this.unselect($(e.target));
  1576. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1577. this.close();
  1578. this.focusSearch();
  1579. })).dequeue();
  1580. killEvent(e);
  1581. })).bind("focus", this.bind(function () {
  1582. if (!this.enabled) return;
  1583. this.container.addClass("select2-container-active");
  1584. this.dropdown.addClass("select2-drop-active");
  1585. }));
  1586. choice.data("select2-data", data);
  1587. choice.insertBefore(this.searchContainer);
  1588. val.push(id);
  1589. this.setVal(val);
  1590. },
  1591. // multi
  1592. unselect: function (selected) {
  1593. var val = this.getVal(),
  1594. data,
  1595. index;
  1596. selected = selected.closest(".select2-search-choice");
  1597. if (selected.length === 0) {
  1598. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1599. }
  1600. data = selected.data("select2-data");
  1601. index = indexOf(this.id(data), val);
  1602. if (index >= 0) {
  1603. val.splice(index, 1);
  1604. this.setVal(val);
  1605. if (this.select) this.postprocessResults();
  1606. }
  1607. selected.remove();
  1608. this.triggerChange({ removed: data });
  1609. },
  1610. // multi
  1611. postprocessResults: function () {
  1612. var val = this.getVal(),
  1613. choices = this.results.find(".select2-result-selectable"),
  1614. compound = this.results.find(".select2-result-with-children"),
  1615. self = this;
  1616. choices.each2(function (i, choice) {
  1617. var id = self.id(choice.data("select2-data"));
  1618. if (indexOf(id, val) >= 0) {
  1619. choice.addClass("select2-disabled").removeClass("select2-result-selectable");
  1620. } else {
  1621. choice.removeClass("select2-disabled").addClass("select2-result-selectable");
  1622. }
  1623. });
  1624. compound.each2(function(i, e) {
  1625. if (e.find(".select2-result-selectable").length==0) {
  1626. e.addClass("select2-disabled");
  1627. } else {
  1628. e.removeClass("select2-disabled");
  1629. }
  1630. });
  1631. choices.each2(function (i, choice) {
  1632. if (!choice.hasClass("select2-disabled") && choice.hasClass("select2-result-selectable")) {
  1633. self.highlight(0);
  1634. return false;
  1635. }
  1636. });
  1637. },
  1638. // multi
  1639. resizeSearch: function () {
  1640. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  1641. sideBorderPadding = getSideBorderPadding(this.search);
  1642. minimumWidth = measureTextWidth(this.search) + 10;
  1643. left = this.search.offset().left;
  1644. maxWidth = this.selection.width();
  1645. containerLeft = this.selection.offset().left;
  1646. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  1647. if (searchWidth < minimumWidth) {
  1648. searchWidth = maxWidth - sideBorderPadding;
  1649. }
  1650. if (searchWidth < 40) {
  1651. searchWidth = maxWidth - sideBorderPadding;
  1652. }
  1653. this.search.width(searchWidth);
  1654. },
  1655. // multi
  1656. getVal: function () {
  1657. var val;
  1658. if (this.select) {
  1659. val = this.select.val();
  1660. return val === null ? [] : val;
  1661. } else {
  1662. val = this.opts.element.val();
  1663. return splitVal(val, this.opts.separator);
  1664. }
  1665. },
  1666. // multi
  1667. setVal: function (val) {
  1668. var unique;
  1669. if (this.select) {
  1670. this.select.val(val);
  1671. } else {
  1672. unique = [];
  1673. // filter out duplicates
  1674. $(val).each(function () {
  1675. if (indexOf(this, unique) < 0) unique.push(this);
  1676. });
  1677. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  1678. }
  1679. },
  1680. // multi
  1681. val: function () {
  1682. var val, data = [], self=this;
  1683. if (arguments.length === 0) {
  1684. return this.getVal();
  1685. }
  1686. val = arguments[0];
  1687. if (!val) {
  1688. this.opts.element.val("");
  1689. this.updateSelection([]);
  1690. this.clearSearch();
  1691. return;
  1692. }
  1693. // val is a list of ids
  1694. this.setVal(val);
  1695. if (this.select) {
  1696. this.select.find(":selected").each(function () {
  1697. data.push({id: $(this).attr("value"), text: $(this).text()});
  1698. });
  1699. this.updateSelection(data);
  1700. } else {
  1701. if (this.opts.initSelection === undefined) {
  1702. throw new Error("val() cannot be called if initSelection() is not defined")
  1703. }
  1704. this.opts.initSelection(this.opts.element, function(data){
  1705. var ids=$(data).map(self.id);
  1706. self.setVal(ids);
  1707. self.updateSelection(data);
  1708. self.clearSearch();
  1709. });
  1710. }
  1711. this.clearSearch();
  1712. },
  1713. // multi
  1714. onSortStart: function() {
  1715. if (this.select) {
  1716. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  1717. }
  1718. // collapse search field into 0 width so its container can be collapsed as well
  1719. this.search.width(0);
  1720. // hide the container
  1721. this.searchContainer.hide();
  1722. },
  1723. // multi
  1724. onSortEnd:function() {
  1725. var val=[], self=this;
  1726. // show search and move it to the end of the list
  1727. this.searchContainer.show();
  1728. // make sure the search container is the last item in the list
  1729. this.searchContainer.appendTo(this.searchContainer.parent());
  1730. // since we collapsed the width in dragStarted, we resize it here
  1731. this.resizeSearch();
  1732. // update selection
  1733. this.selection.find(".select2-search-choice").each(function() {
  1734. val.push(self.opts.id($(this).data("select2-data")));
  1735. });
  1736. this.setVal(val);
  1737. this.triggerChange();
  1738. },
  1739. // multi
  1740. data: function(values) {
  1741. var self=this, ids;
  1742. if (arguments.length === 0) {
  1743. return this.selection
  1744. .find(".select2-search-choice")
  1745. .map(function() { return $(this).data("select2-data"); })
  1746. .get();
  1747. } else {
  1748. if (!values) { values = []; }
  1749. ids = $.map(values, function(e) { return self.opts.id(e)});
  1750. this.setVal(ids);
  1751. this.updateSelection(values);
  1752. this.clearSearch();
  1753. }
  1754. }
  1755. });
  1756. $.fn.select2 = function () {
  1757. var args = Array.prototype.slice.call(arguments, 0),
  1758. opts,
  1759. select2,
  1760. value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
  1761. this.each(function () {
  1762. if (args.length === 0 || typeof(args[0]) === "object") {
  1763. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1764. opts.element = $(this);
  1765. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1766. multiple = opts.element.attr("multiple");
  1767. } else {
  1768. multiple = opts.multiple || false;
  1769. if ("tags" in opts) {opts.multiple = multiple = true;}
  1770. }
  1771. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1772. select2.init(opts);
  1773. } else if (typeof(args[0]) === "string") {
  1774. if (indexOf(args[0], allowedMethods) < 0) {
  1775. throw "Unknown method: " + args[0];
  1776. }
  1777. value = undefined;
  1778. select2 = $(this).data("select2");
  1779. if (select2 === undefined) return;
  1780. if (args[0] === "container") {
  1781. value=select2.container;
  1782. } else {
  1783. value = select2[args[0]].apply(select2, args.slice(1));
  1784. }
  1785. if (value !== undefined) {return false;}
  1786. } else {
  1787. throw "Invalid arguments to select2 plugin: " + args;
  1788. }
  1789. });
  1790. return (value === undefined) ? this : value;
  1791. };
  1792. // plugin defaults, accessible to users
  1793. $.fn.select2.defaults = {
  1794. width: "copy",
  1795. closeOnSelect: true,
  1796. containerCss: {},
  1797. dropdownCss: {},
  1798. containerCssClass: "",
  1799. dropdownCssClass: "",
  1800. formatResult: function(result, container, query) {
  1801. var markup=[];
  1802. markMatch(result.text, query.term, markup);
  1803. return markup.join("");
  1804. },
  1805. formatSelection: function (data, container) {
  1806. return data.text;
  1807. },
  1808. formatNoMatches: function () { return "No matches found"; },
  1809. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  1810. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " items"; },
  1811. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  1812. minimumResultsForSearch: 0,
  1813. minimumInputLength: 0,
  1814. maximumSelectionSize: 0,
  1815. id: function (e) { return e.id; },
  1816. matcher: function(term, text) {
  1817. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  1818. }
  1819. };
  1820. // exports
  1821. window.Select2 = {
  1822. query: {
  1823. ajax: ajax,
  1824. local: local,
  1825. tags: tags
  1826. }, util: {
  1827. debounce: debounce,
  1828. markMatch: markMatch
  1829. }, "class": {
  1830. "abstract": AbstractSelect2,
  1831. "single": SingleSelect2,
  1832. "multi": MultiSelect2
  1833. }
  1834. };
  1835. }(jQuery));