select2.js 80 KB

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