select2.js 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206
  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") || opts.element.is("[readonly='readonly']")) 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)
  1147. || e.which === KEY.ESC || e.which == KEY.ENTER) {
  1148. return;
  1149. }
  1150. if (e.which == KEY.DELETE) {
  1151. if (this.opts.allowClear) {
  1152. this.clear();
  1153. }
  1154. return;
  1155. }
  1156. this.open();
  1157. if (e.which === KEY.ENTER) {
  1158. // do not propagate the event otherwise we open, and propagate enter which closes
  1159. killEvent(e);
  1160. return;
  1161. }
  1162. // do not set the search input value for non-alpha-numeric keys
  1163. // otherwise pressing down results in a '(' being set in the search field
  1164. if (e.which < 48 ) { // '0' == 48
  1165. killEvent(e);
  1166. return;
  1167. }
  1168. var keyWritten = String.fromCharCode(e.which).toLowerCase();
  1169. if (e.shiftKey) {
  1170. keyWritten = keyWritten.toUpperCase();
  1171. }
  1172. this.search.val(keyWritten);
  1173. // prevent event propagation so it doesnt replay on the now focussed search field and result in double key entry
  1174. killEvent(e);
  1175. }));
  1176. selection.delegate("abbr", "mousedown", this.bind(function (e) {
  1177. if (!this.enabled) return;
  1178. this.clear();
  1179. killEvent(e);
  1180. this.close();
  1181. this.triggerChange();
  1182. this.selection.focus();
  1183. }));
  1184. this.setPlaceholder();
  1185. this.search.bind("focus", this.bind(function() {
  1186. this.container.addClass("select2-container-active");
  1187. }));
  1188. },
  1189. // single
  1190. clear: function() {
  1191. this.opts.element.val("");
  1192. this.selection.find("span").empty();
  1193. this.selection.removeData("select2-data");
  1194. this.setPlaceholder();
  1195. },
  1196. /**
  1197. * Sets selection based on source element's value
  1198. */
  1199. // single
  1200. initSelection: function () {
  1201. var selected;
  1202. if (this.opts.element.val() === "") {
  1203. this.close();
  1204. this.setPlaceholder();
  1205. } else {
  1206. var self = this;
  1207. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1208. if (selected !== undefined && selected !== null) {
  1209. self.updateSelection(selected);
  1210. self.close();
  1211. self.setPlaceholder();
  1212. }
  1213. });
  1214. }
  1215. },
  1216. // single
  1217. prepareOpts: function () {
  1218. var opts = this.parent.prepareOpts.apply(this, arguments);
  1219. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1220. // install the selection initializer
  1221. opts.initSelection = function (element, callback) {
  1222. var selected = element.find(":selected");
  1223. // a single select box always has a value, no need to null check 'selected'
  1224. if ($.isFunction(callback))
  1225. callback({id: selected.attr("value"), text: selected.text()});
  1226. };
  1227. }
  1228. return opts;
  1229. },
  1230. // single
  1231. setPlaceholder: function () {
  1232. var placeholder = this.getPlaceholder();
  1233. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1234. // check for a first blank option if attached to a select
  1235. if (this.select && this.select.find("option:first").text() !== "") return;
  1236. this.selection.find("span").html(escapeMarkup(placeholder));
  1237. this.selection.addClass("select2-default");
  1238. this.selection.find("abbr").hide();
  1239. }
  1240. },
  1241. // single
  1242. postprocessResults: function (data, initial) {
  1243. var selected = 0, self = this, showSearchInput = true;
  1244. // find the selected element in the result list
  1245. this.results.find(".select2-result-selectable").each2(function (i, elm) {
  1246. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1247. selected = i;
  1248. return false;
  1249. }
  1250. });
  1251. // and highlight it
  1252. this.highlight(selected);
  1253. // hide the search box if this is the first we got the results and there are a few of them
  1254. if (initial === true) {
  1255. // TODO below we use data.results.length, but what we really need is something recursive to calc the length
  1256. // TODO in case there are optgroups
  1257. showSearchInput = this.showSearchInput = data.results.length >= this.opts.minimumResultsForSearch;
  1258. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1259. //add "select2-with-searchbox" to the container if search box is shown
  1260. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1261. }
  1262. },
  1263. // single
  1264. onSelect: function (data) {
  1265. var old = this.opts.element.val();
  1266. this.opts.element.val(this.id(data));
  1267. this.updateSelection(data);
  1268. this.close();
  1269. this.selection.focus();
  1270. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1271. },
  1272. // single
  1273. updateSelection: function (data) {
  1274. var container=this.selection.find("span"), formatted;
  1275. this.selection.data("select2-data", data);
  1276. container.empty();
  1277. formatted=this.opts.formatSelection(data, container);
  1278. if (formatted !== undefined) {
  1279. container.append(escapeMarkup(formatted));
  1280. }
  1281. this.selection.removeClass("select2-default");
  1282. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1283. this.selection.find("abbr").show();
  1284. }
  1285. },
  1286. // single
  1287. val: function () {
  1288. var val, data = null, self = this;
  1289. if (arguments.length === 0) {
  1290. return this.opts.element.val();
  1291. }
  1292. val = arguments[0];
  1293. if (this.select) {
  1294. this.select
  1295. .val(val)
  1296. .find(":selected").each2(function (i, elm) {
  1297. data = {id: elm.attr("value"), text: elm.text()};
  1298. return false;
  1299. });
  1300. this.updateSelection(data);
  1301. this.setPlaceholder();
  1302. } else {
  1303. if (this.opts.initSelection === undefined) {
  1304. throw new Error("cannot call val() if initSelection() is not defined");
  1305. }
  1306. // val is an id. !val is true for [undefined,null,'']
  1307. if (!val) {
  1308. this.clear();
  1309. return;
  1310. }
  1311. this.opts.initSelection(this.opts.element, function(data){
  1312. self.opts.element.val(!data ? "" : self.id(data));
  1313. self.updateSelection(data);
  1314. self.setPlaceholder();
  1315. });
  1316. }
  1317. },
  1318. // single
  1319. clearSearch: function () {
  1320. this.search.val("");
  1321. },
  1322. // single
  1323. data: function(value) {
  1324. var data;
  1325. if (arguments.length === 0) {
  1326. data = this.selection.data("select2-data");
  1327. if (data == undefined) data = null;
  1328. return data;
  1329. } else {
  1330. if (!value || value === "") {
  1331. this.clear();
  1332. } else {
  1333. this.opts.element.val(!value ? "" : this.id(value));
  1334. this.updateSelection(value);
  1335. }
  1336. }
  1337. }
  1338. });
  1339. MultiSelect2 = clazz(AbstractSelect2, {
  1340. // multi
  1341. createContainer: function () {
  1342. var container = $("<div></div>", {
  1343. "class": "select2-container select2-container-multi"
  1344. }).html([
  1345. " <ul class='select2-choices'>",
  1346. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1347. " <li class='select2-search-field'>" ,
  1348. " <input type='text' autocomplete='off' style='width: 25px;' class='select2-input'>" ,
  1349. " </li>" ,
  1350. "</ul>" ,
  1351. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1352. " <ul class='select2-results'>" ,
  1353. " </ul>" ,
  1354. "</div>"].join(""));
  1355. return container;
  1356. },
  1357. // multi
  1358. prepareOpts: function () {
  1359. var opts = this.parent.prepareOpts.apply(this, arguments);
  1360. // TODO validate placeholder is a string if specified
  1361. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1362. // install sthe selection initializer
  1363. opts.initSelection = function (element,callback) {
  1364. var data = [];
  1365. element.find(":selected").each2(function (i, elm) {
  1366. data.push({id: elm.attr("value"), text: elm.text()});
  1367. });
  1368. if ($.isFunction(callback))
  1369. callback(data);
  1370. };
  1371. }
  1372. return opts;
  1373. },
  1374. // multi
  1375. initContainer: function () {
  1376. var selector = ".select2-choices", selection;
  1377. this.searchContainer = this.container.find(".select2-search-field");
  1378. this.selection = selection = this.container.find(selector);
  1379. this.search.bind("keydown", this.bind(function (e) {
  1380. if (!this.enabled) return;
  1381. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1382. this.close();
  1383. var choices,
  1384. selected = selection.find(".select2-search-choice-focus");
  1385. if (selected.length > 0) {
  1386. this.unselect(selected.first());
  1387. this.search.width(10);
  1388. killEvent(e);
  1389. return;
  1390. }
  1391. choices = selection.find(".select2-search-choice");
  1392. if (choices.length > 0) {
  1393. choices.last().addClass("select2-search-choice-focus");
  1394. }
  1395. } else {
  1396. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1397. }
  1398. if (this.opened()) {
  1399. switch (e.which) {
  1400. case KEY.UP:
  1401. case KEY.DOWN:
  1402. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1403. killEvent(e);
  1404. return;
  1405. case KEY.ENTER:
  1406. case KEY.TAB:
  1407. this.selectHighlighted();
  1408. killEvent(e);
  1409. return;
  1410. case KEY.ESC:
  1411. this.cancel(e);
  1412. killEvent(e);
  1413. return;
  1414. }
  1415. }
  1416. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  1417. || e.which === KEY.BACKSPACE || e.which === KEY.ESC || e.which === KEY.ENTER) {
  1418. return;
  1419. }
  1420. this.open();
  1421. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1422. // prevent the page from scrolling
  1423. killEvent(e);
  1424. }
  1425. }));
  1426. this.search.bind("keyup", this.bind(this.resizeSearch));
  1427. this.search.bind("blur", this.bind(function() {
  1428. this.container.removeClass("select2-container-active");
  1429. }));
  1430. this.container.delegate(selector, "mousedown", this.bind(function (e) {
  1431. if (!this.enabled) return;
  1432. this.clearPlaceholder();
  1433. this.open();
  1434. this.focusSearch();
  1435. e.preventDefault();
  1436. }));
  1437. this.container.delegate(selector, "focus", this.bind(function () {
  1438. if (!this.enabled) return;
  1439. this.container.addClass("select2-container-active");
  1440. this.dropdown.addClass("select2-drop-active");
  1441. this.clearPlaceholder();
  1442. }));
  1443. // set the placeholder if necessary
  1444. this.clearSearch();
  1445. },
  1446. // multi
  1447. enable: function() {
  1448. if (this.enabled) return;
  1449. this.parent.enable.apply(this, arguments);
  1450. this.search.removeAttr("disabled");
  1451. },
  1452. // multi
  1453. disable: function() {
  1454. if (!this.enabled) return;
  1455. this.parent.disable.apply(this, arguments);
  1456. this.search.attr("disabled", true);
  1457. },
  1458. // multi
  1459. initSelection: function () {
  1460. var data;
  1461. if (this.opts.element.val() === "") {
  1462. this.updateSelection([]);
  1463. this.close();
  1464. // set the placeholder if necessary
  1465. this.clearSearch();
  1466. }
  1467. if (this.select || this.opts.element.val() !== "") {
  1468. var self = this;
  1469. this.opts.initSelection.call(null, this.opts.element, function(data){
  1470. if (data !== undefined && data !== null) {
  1471. self.updateSelection(data);
  1472. self.close();
  1473. // set the placeholder if necessary
  1474. self.clearSearch();
  1475. }
  1476. });
  1477. }
  1478. },
  1479. // multi
  1480. clearSearch: function () {
  1481. var placeholder = this.getPlaceholder();
  1482. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1483. this.search.val(placeholder).addClass("select2-default");
  1484. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1485. this.resizeSearch();
  1486. } else {
  1487. // we set this to " " instead of "" and later clear it on focus() because there is a firefox bug
  1488. // that does not properly render the caret when the field starts out blank
  1489. this.search.val(" ").width(10);
  1490. }
  1491. },
  1492. // multi
  1493. clearPlaceholder: function () {
  1494. if (this.search.hasClass("select2-default")) {
  1495. this.search.val("").removeClass("select2-default");
  1496. } else {
  1497. // work around for the space character we set to avoid firefox caret bug
  1498. if (this.search.val() === " ") this.search.val("");
  1499. }
  1500. },
  1501. // multi
  1502. opening: function () {
  1503. this.parent.opening.apply(this, arguments);
  1504. this.clearPlaceholder();
  1505. this.resizeSearch();
  1506. this.focusSearch();
  1507. },
  1508. // multi
  1509. close: function () {
  1510. if (!this.opened()) return;
  1511. this.parent.close.apply(this, arguments);
  1512. },
  1513. // multi
  1514. focus: function () {
  1515. this.close();
  1516. this.search.focus();
  1517. },
  1518. // multi
  1519. isFocused: function () {
  1520. return this.search.hasClass("select2-focused");
  1521. },
  1522. // multi
  1523. updateSelection: function (data) {
  1524. var ids = [], filtered = [], self = this;
  1525. // filter out duplicates
  1526. $(data).each(function () {
  1527. if (indexOf(self.id(this), ids) < 0) {
  1528. ids.push(self.id(this));
  1529. filtered.push(this);
  1530. }
  1531. });
  1532. data = filtered;
  1533. this.selection.find(".select2-search-choice").remove();
  1534. $(data).each(function () {
  1535. self.addSelectedChoice(this);
  1536. });
  1537. self.postprocessResults();
  1538. },
  1539. // multi
  1540. onSelect: function (data) {
  1541. this.addSelectedChoice(data);
  1542. if (this.select) { this.postprocessResults(); }
  1543. if (this.opts.closeOnSelect) {
  1544. this.close();
  1545. this.search.width(10);
  1546. } else {
  1547. this.search.width(10);
  1548. this.resizeSearch();
  1549. if (this.countSelectableResults()>0) {
  1550. this.positionDropdown();
  1551. } else {
  1552. // if nothing left to select close
  1553. this.close();
  1554. }
  1555. }
  1556. // since its not possible to select an element that has already been
  1557. // added we do not need to check if this is a new element before firing change
  1558. this.triggerChange({ added: data });
  1559. this.focusSearch();
  1560. },
  1561. // multi
  1562. cancel: function () {
  1563. this.close();
  1564. this.focusSearch();
  1565. },
  1566. // multi
  1567. addSelectedChoice: function (data) {
  1568. var choice=$(
  1569. "<li class='select2-search-choice'>" +
  1570. " <div></div>" +
  1571. " <a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>" +
  1572. "</li>"),
  1573. id = this.id(data),
  1574. val = this.getVal(),
  1575. formatted;
  1576. formatted=this.opts.formatSelection(data, choice);
  1577. choice.find("div").replaceWith("<div>"+escapeMarkup(formatted)+"</div>");
  1578. choice.find(".select2-search-choice-close")
  1579. .bind("mousedown", killEvent)
  1580. .bind("click dblclick", this.bind(function (e) {
  1581. if (!this.enabled) return;
  1582. $(e.target).closest(".select2-search-choice").fadeOut('fast').animate({width: "hide"}, 50, this.bind(function(){
  1583. this.unselect($(e.target));
  1584. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1585. this.close();
  1586. this.focusSearch();
  1587. })).dequeue();
  1588. killEvent(e);
  1589. })).bind("focus", this.bind(function () {
  1590. if (!this.enabled) return;
  1591. this.container.addClass("select2-container-active");
  1592. this.dropdown.addClass("select2-drop-active");
  1593. }));
  1594. choice.data("select2-data", data);
  1595. choice.insertBefore(this.searchContainer);
  1596. val.push(id);
  1597. this.setVal(val);
  1598. },
  1599. // multi
  1600. unselect: function (selected) {
  1601. var val = this.getVal(),
  1602. data,
  1603. index;
  1604. selected = selected.closest(".select2-search-choice");
  1605. if (selected.length === 0) {
  1606. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1607. }
  1608. data = selected.data("select2-data");
  1609. index = indexOf(this.id(data), val);
  1610. if (index >= 0) {
  1611. val.splice(index, 1);
  1612. this.setVal(val);
  1613. if (this.select) this.postprocessResults();
  1614. }
  1615. selected.remove();
  1616. this.triggerChange({ removed: data });
  1617. },
  1618. // multi
  1619. postprocessResults: function () {
  1620. var val = this.getVal(),
  1621. choices = this.results.find(".select2-result-selectable"),
  1622. compound = this.results.find(".select2-result-with-children"),
  1623. self = this;
  1624. choices.each2(function (i, choice) {
  1625. var id = self.id(choice.data("select2-data"));
  1626. if (indexOf(id, val) >= 0) {
  1627. choice.addClass("select2-disabled").removeClass("select2-result-selectable");
  1628. } else {
  1629. choice.removeClass("select2-disabled").addClass("select2-result-selectable");
  1630. }
  1631. });
  1632. compound.each2(function(i, e) {
  1633. if (e.find(".select2-result-selectable").length==0) {
  1634. e.addClass("select2-disabled");
  1635. } else {
  1636. e.removeClass("select2-disabled");
  1637. }
  1638. });
  1639. choices.each2(function (i, choice) {
  1640. if (!choice.hasClass("select2-disabled") && choice.hasClass("select2-result-selectable")) {
  1641. self.highlight(0);
  1642. return false;
  1643. }
  1644. });
  1645. },
  1646. // multi
  1647. resizeSearch: function () {
  1648. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  1649. sideBorderPadding = getSideBorderPadding(this.search);
  1650. minimumWidth = measureTextWidth(this.search) + 10;
  1651. left = this.search.offset().left;
  1652. maxWidth = this.selection.width();
  1653. containerLeft = this.selection.offset().left;
  1654. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  1655. if (searchWidth < minimumWidth) {
  1656. searchWidth = maxWidth - sideBorderPadding;
  1657. }
  1658. if (searchWidth < 40) {
  1659. searchWidth = maxWidth - sideBorderPadding;
  1660. }
  1661. this.search.width(searchWidth);
  1662. },
  1663. // multi
  1664. getVal: function () {
  1665. var val;
  1666. if (this.select) {
  1667. val = this.select.val();
  1668. return val === null ? [] : val;
  1669. } else {
  1670. val = this.opts.element.val();
  1671. return splitVal(val, this.opts.separator);
  1672. }
  1673. },
  1674. // multi
  1675. setVal: function (val) {
  1676. var unique;
  1677. if (this.select) {
  1678. this.select.val(val);
  1679. } else {
  1680. unique = [];
  1681. // filter out duplicates
  1682. $(val).each(function () {
  1683. if (indexOf(this, unique) < 0) unique.push(this);
  1684. });
  1685. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  1686. }
  1687. },
  1688. // multi
  1689. val: function () {
  1690. var val, data = [], self=this;
  1691. if (arguments.length === 0) {
  1692. return this.getVal();
  1693. }
  1694. val = arguments[0];
  1695. if (!val) {
  1696. this.opts.element.val("");
  1697. this.updateSelection([]);
  1698. this.clearSearch();
  1699. return;
  1700. }
  1701. // val is a list of ids
  1702. this.setVal(val);
  1703. if (this.select) {
  1704. this.select.find(":selected").each(function () {
  1705. data.push({id: $(this).attr("value"), text: $(this).text()});
  1706. });
  1707. this.updateSelection(data);
  1708. } else {
  1709. if (this.opts.initSelection === undefined) {
  1710. throw new Error("val() cannot be called if initSelection() is not defined")
  1711. }
  1712. this.opts.initSelection(this.opts.element, function(data){
  1713. var ids=$(data).map(self.id);
  1714. self.setVal(ids);
  1715. self.updateSelection(data);
  1716. self.clearSearch();
  1717. });
  1718. }
  1719. this.clearSearch();
  1720. },
  1721. // multi
  1722. onSortStart: function() {
  1723. if (this.select) {
  1724. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  1725. }
  1726. // collapse search field into 0 width so its container can be collapsed as well
  1727. this.search.width(0);
  1728. // hide the container
  1729. this.searchContainer.hide();
  1730. },
  1731. // multi
  1732. onSortEnd:function() {
  1733. var val=[], self=this;
  1734. // show search and move it to the end of the list
  1735. this.searchContainer.show();
  1736. // make sure the search container is the last item in the list
  1737. this.searchContainer.appendTo(this.searchContainer.parent());
  1738. // since we collapsed the width in dragStarted, we resize it here
  1739. this.resizeSearch();
  1740. // update selection
  1741. this.selection.find(".select2-search-choice").each(function() {
  1742. val.push(self.opts.id($(this).data("select2-data")));
  1743. });
  1744. this.setVal(val);
  1745. this.triggerChange();
  1746. },
  1747. // multi
  1748. data: function(values) {
  1749. var self=this, ids;
  1750. if (arguments.length === 0) {
  1751. return this.selection
  1752. .find(".select2-search-choice")
  1753. .map(function() { return $(this).data("select2-data"); })
  1754. .get();
  1755. } else {
  1756. if (!values) { values = []; }
  1757. ids = $.map(values, function(e) { return self.opts.id(e)});
  1758. this.setVal(ids);
  1759. this.updateSelection(values);
  1760. this.clearSearch();
  1761. }
  1762. }
  1763. });
  1764. $.fn.select2 = function () {
  1765. var args = Array.prototype.slice.call(arguments, 0),
  1766. opts,
  1767. select2,
  1768. value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
  1769. this.each(function () {
  1770. if (args.length === 0 || typeof(args[0]) === "object") {
  1771. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1772. opts.element = $(this);
  1773. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1774. multiple = opts.element.attr("multiple");
  1775. } else {
  1776. multiple = opts.multiple || false;
  1777. if ("tags" in opts) {opts.multiple = multiple = true;}
  1778. }
  1779. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1780. select2.init(opts);
  1781. } else if (typeof(args[0]) === "string") {
  1782. if (indexOf(args[0], allowedMethods) < 0) {
  1783. throw "Unknown method: " + args[0];
  1784. }
  1785. value = undefined;
  1786. select2 = $(this).data("select2");
  1787. if (select2 === undefined) return;
  1788. if (args[0] === "container") {
  1789. value=select2.container;
  1790. } else {
  1791. value = select2[args[0]].apply(select2, args.slice(1));
  1792. }
  1793. if (value !== undefined) {return false;}
  1794. } else {
  1795. throw "Invalid arguments to select2 plugin: " + args;
  1796. }
  1797. });
  1798. return (value === undefined) ? this : value;
  1799. };
  1800. // plugin defaults, accessible to users
  1801. $.fn.select2.defaults = {
  1802. width: "copy",
  1803. closeOnSelect: true,
  1804. containerCss: {},
  1805. dropdownCss: {},
  1806. containerCssClass: "",
  1807. dropdownCssClass: "",
  1808. formatResult: function(result, container, query) {
  1809. var markup=[];
  1810. markMatch(result.text, query.term, markup);
  1811. return markup.join("");
  1812. },
  1813. formatSelection: function (data, container) {
  1814. return data.text;
  1815. },
  1816. formatNoMatches: function () { return "No matches found"; },
  1817. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  1818. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " items"; },
  1819. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  1820. minimumResultsForSearch: 0,
  1821. minimumInputLength: 0,
  1822. maximumSelectionSize: 0,
  1823. id: function (e) { return e.id; },
  1824. matcher: function(term, text) {
  1825. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  1826. }
  1827. };
  1828. // exports
  1829. window.Select2 = {
  1830. query: {
  1831. ajax: ajax,
  1832. local: local,
  1833. tags: tags
  1834. }, util: {
  1835. debounce: debounce,
  1836. markMatch: markMatch
  1837. }, "class": {
  1838. "abstract": AbstractSelect2,
  1839. "single": SingleSelect2,
  1840. "multi": MultiSelect2
  1841. }
  1842. };
  1843. }(jQuery));