select2.js 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  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. return false;
  75. },
  76. isFunctionKey: function (k) {
  77. k = k.which ? k.which : k;
  78. return k >= 112 && k <= 123;
  79. }
  80. };
  81. nextUid=(function() { var counter=1; return function() { return counter++; }; }());
  82. function indexOf(value, array) {
  83. var i = 0, l = array.length, v;
  84. if (typeof value === "undefined") {
  85. return -1;
  86. }
  87. if (value.constructor === String) {
  88. for (; i < l; i = i + 1) if (value.localeCompare(array[i]) === 0) return i;
  89. } else {
  90. for (; i < l; i = i + 1) {
  91. v = array[i];
  92. if (v.constructor === String) {
  93. if (v.localeCompare(value) === 0) return i;
  94. } else {
  95. if (v === value) return i;
  96. }
  97. }
  98. }
  99. return -1;
  100. }
  101. /**
  102. * Compares equality of a and b taking into account that a and b may be strings, in which case localeCompare is used
  103. * @param a
  104. * @param b
  105. */
  106. function equal(a, b) {
  107. if (a === b) return true;
  108. if (a === undefined || b === undefined) return false;
  109. if (a === null || b === null) return false;
  110. if (a.constructor === String) return a.localeCompare(b) === 0;
  111. if (b.constructor === String) return b.localeCompare(a) === 0;
  112. return false;
  113. }
  114. /**
  115. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  116. * strings
  117. * @param string
  118. * @param separator
  119. */
  120. function splitVal(string, separator) {
  121. var val, i, l;
  122. if (string === null || string.length < 1) return [];
  123. val = string.split(separator);
  124. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  125. return val;
  126. }
  127. function getSideBorderPadding(element) {
  128. return element.outerWidth() - element.width();
  129. }
  130. function installKeyUpChangeEvent(element) {
  131. element.bind("keydown", function () {
  132. element.data("keyup-change-value", element.val());
  133. });
  134. element.bind("keyup", function () {
  135. if (element.val() !== element.data("keyup-change-value")) {
  136. element.trigger("keyup-change");
  137. }
  138. });
  139. }
  140. $(document).delegate("*", "mousemove", function (e) {
  141. $(document).data("select2-lastpos", {x: e.pageX, y: e.pageY});
  142. });
  143. /**
  144. * filters mouse events so an event is fired only if the mouse moved.
  145. *
  146. * filters out mouse events that occur when mouse is stationary but
  147. * the elements under the pointer are scrolled.
  148. */
  149. function installFilteredMouseMove(element) {
  150. element.bind("mousemove", function (e) {
  151. var lastpos = $(document).data("select2-lastpos");
  152. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  153. $(e.target).trigger("mousemove-filtered", e);
  154. }
  155. });
  156. }
  157. /**
  158. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  159. * within the last quietMillis milliseconds.
  160. *
  161. * @param quietMillis number of milliseconds to wait before invoking fn
  162. * @param fn function to be debounced
  163. * @return debounced version of fn
  164. */
  165. function debounce(quietMillis, fn) {
  166. var timeout;
  167. return function () {
  168. window.clearTimeout(timeout);
  169. timeout = window.setTimeout(fn, quietMillis);
  170. };
  171. }
  172. function installDebouncedScroll(threshold, element) {
  173. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  174. element.bind("scroll", function (e) {
  175. if (indexOf(e.target, element.get()) >= 0) notify(e);
  176. });
  177. }
  178. function killEvent(event) {
  179. event.preventDefault();
  180. event.stopPropagation();
  181. }
  182. function measureTextWidth(e) {
  183. if (!sizer){
  184. var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
  185. sizer = $("<div></div>").css({
  186. position: "absolute",
  187. left: "-1000px",
  188. top: "-1000px",
  189. display: "none",
  190. fontSize: style.fontSize,
  191. fontFamily: style.fontFamily,
  192. fontStyle: style.fontStyle,
  193. fontWeight: style.fontWeight,
  194. letterSpacing: style.letterSpacing,
  195. textTransform: style.textTransform,
  196. whiteSpace: "nowrap"
  197. });
  198. $("body").append(sizer);
  199. }
  200. sizer.text(e.val());
  201. return sizer.width();
  202. }
  203. function markMatch(text, term, markup) {
  204. var match=text.toUpperCase().indexOf(term.toUpperCase()),
  205. tl=term.length;
  206. if (match<0) {
  207. markup.push(text);
  208. return;
  209. }
  210. markup.push(text.substring(0, match));
  211. markup.push("<span class='select2-match'>");
  212. markup.push(text.substring(match, match + tl));
  213. markup.push("</span>");
  214. markup.push(text.substring(match + tl, text.length));
  215. }
  216. /**
  217. * Produces an ajax-based query function
  218. *
  219. * @param options object containing configuration paramters
  220. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  221. * @param options.url url for the data
  222. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  223. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
  224. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  225. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  226. * The expected format is an object containing the following keys:
  227. * results array of objects that will be used as choices
  228. * more (optional) boolean indicating whether there are more results available
  229. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  230. */
  231. function ajax(options) {
  232. var timeout, // current scheduled but not yet executed request
  233. requestSequence = 0, // sequence used to drop out-of-order responses
  234. handler = null,
  235. quietMillis = options.quietMillis || 100;
  236. return function (query) {
  237. window.clearTimeout(timeout);
  238. timeout = window.setTimeout(function () {
  239. requestSequence += 1; // increment the sequence
  240. var requestNumber = requestSequence, // this request's sequence number
  241. data = options.data, // ajax data function
  242. transport = options.transport || $.ajax,
  243. type = options.type || 'GET'; // set type of request (GET or POST)
  244. data = data.call(this, query.term, query.page, query.context);
  245. if( null !== handler) { handler.abort(); }
  246. handler = transport.call(null, {
  247. url: options.url,
  248. dataType: options.dataType,
  249. data: data,
  250. type: type,
  251. success: function (data) {
  252. if (requestNumber < requestSequence) {
  253. return;
  254. }
  255. // TODO 3.0 - replace query.page with query so users have access to term, page, etc.
  256. var results = options.results(data, query.page);
  257. query.callback(results);
  258. }
  259. });
  260. }, quietMillis);
  261. };
  262. }
  263. /**
  264. * Produces a query function that works with a local array
  265. *
  266. * @param options object containing configuration parameters. The options parameter can either be an array or an
  267. * object.
  268. *
  269. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  270. *
  271. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  272. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  273. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  274. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  275. * the text.
  276. */
  277. function local(options) {
  278. var data = options, // data elements
  279. dataText,
  280. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  281. if (!$.isArray(data)) {
  282. text = data.text;
  283. // if text is not a function we assume it to be a key name
  284. if (!$.isFunction(text)) {
  285. 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
  286. text = function (item) { return item[dataText]; };
  287. }
  288. data = data.results;
  289. }
  290. return function (query) {
  291. var t = query.term, filtered = {};
  292. if (t === "") {
  293. query.callback({results: data});
  294. return;
  295. }
  296. filtered.results = $(data)
  297. .filter(function () {return query.matcher(t, text(this));})
  298. .get();
  299. query.callback(filtered);
  300. };
  301. }
  302. // TODO javadoc
  303. function tags(data) {
  304. // TODO even for a function we should probably return a wrapper that does the same object/string check as
  305. // the function for arrays. otherwise only functions that return objects are supported.
  306. if ($.isFunction(data)) {
  307. return data;
  308. }
  309. // if not a function we assume it to be an array
  310. return function (query) {
  311. var t = query.term, filtered = {results: []};
  312. $(data).each(function () {
  313. var isObject = this.text !== undefined,
  314. text = isObject ? this.text : this;
  315. if (t === "" || query.matcher(t, text)) {
  316. filtered.results.push(isObject ? this : {id: this, text: this});
  317. }
  318. });
  319. query.callback(filtered);
  320. };
  321. }
  322. /**
  323. * blurs any Select2 container that has focus when an element outside them was clicked or received focus
  324. */
  325. $(document).ready(function () {
  326. $(document).delegate("*", "mousedown focusin touchend", function (e) {
  327. var target = $(e.target).closest("div.select2-container").get(0);
  328. if (target) {
  329. $(document).find("div.select2-container-active").each(function () {
  330. if (this !== target) $(this).data("select2").blur();
  331. });
  332. } else {
  333. target = $(e.target).closest("div.select2-drop").get(0);
  334. $(document).find("div.select2-drop-active").each(function () {
  335. if (this !== target) $(this).data("select2").blur();
  336. });
  337. }
  338. });
  339. });
  340. function evaluate(val) {
  341. return $.isFunction(val) ? val() : val;
  342. }
  343. /**
  344. * Creates a new class
  345. *
  346. * @param superClass
  347. * @param methods
  348. */
  349. function clazz(SuperClass, methods) {
  350. var constructor = function () {};
  351. constructor.prototype = new SuperClass;
  352. constructor.prototype.constructor = constructor;
  353. constructor.prototype.parent = SuperClass.prototype;
  354. constructor.prototype = $.extend(constructor.prototype, methods);
  355. return constructor;
  356. }
  357. AbstractSelect2 = clazz(Object, {
  358. // abstract
  359. bind: function (func) {
  360. var self = this;
  361. return function () {
  362. func.apply(self, arguments);
  363. };
  364. },
  365. // abstract
  366. init: function (opts) {
  367. var results, search, resultsSelector = ".select2-results";
  368. // prepare options
  369. this.opts = opts = this.prepareOpts(opts);
  370. this.id=opts.id;
  371. // destroy if called on an existing component
  372. if (opts.element.data("select2") !== undefined &&
  373. opts.element.data("select2") !== null) {
  374. this.destroy();
  375. }
  376. this.enabled=true;
  377. this.container = this.createContainer();
  378. this.body = opts.element.closest("body"); // cache for future access
  379. if (opts.element.attr("class") !== undefined) {
  380. this.container.addClass(opts.element.attr("class"));
  381. }
  382. this.container.css(evaluate(opts.containerCss));
  383. this.container.addClass(evaluate(opts.containerCssClass));
  384. // swap container for the element
  385. this.opts.element
  386. .data("select2", this)
  387. .hide()
  388. .after(this.container);
  389. this.container.data("select2", this);
  390. this.dropdown = this.container.find(".select2-drop");
  391. this.dropdown.css(evaluate(opts.dropdownCss));
  392. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  393. this.dropdown.data("select2", this);
  394. this.results = results = this.container.find(resultsSelector);
  395. this.search = search = this.container.find("input.select2-input");
  396. this.resultsPage = 0;
  397. this.context = null;
  398. // initialize the container
  399. this.initContainer();
  400. installFilteredMouseMove(this.results);
  401. this.dropdown.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
  402. installDebouncedScroll(80, this.results);
  403. this.dropdown.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  404. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  405. if ($.fn.mousewheel) {
  406. results.mousewheel(function (e, delta, deltaX, deltaY) {
  407. var top = results.scrollTop(), height;
  408. if (deltaY > 0 && top - deltaY <= 0) {
  409. results.scrollTop(0);
  410. killEvent(e);
  411. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  412. results.scrollTop(results.get(0).scrollHeight - results.height());
  413. killEvent(e);
  414. }
  415. });
  416. }
  417. installKeyUpChangeEvent(search);
  418. search.bind("keyup-change", this.bind(this.updateResults));
  419. search.bind("focus", function () { search.addClass("select2-focused");});
  420. search.bind("blur", function () { search.removeClass("select2-focused");});
  421. this.dropdown.delegate(resultsSelector, "click", this.bind(function (e) {
  422. if ($(e.target).closest(".select2-result:not(.select2-disabled)").length > 0) {
  423. this.highlightUnderEvent(e);
  424. this.selectHighlighted(e);
  425. } else {
  426. killEvent(e);
  427. this.focusSearch();
  428. }
  429. }));
  430. if ($.isFunction(this.opts.initSelection)) {
  431. // initialize selection based on the current value of the source element
  432. this.initSelection();
  433. // if the user has provided a function that can set selection based on the value of the source element
  434. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  435. this.monitorSource();
  436. }
  437. if (opts.element.is(":disabled")) this.disable();
  438. },
  439. // abstract
  440. destroy: function () {
  441. var select2 = this.opts.element.data("select2");
  442. if (select2 !== undefined) {
  443. select2.container.remove();
  444. select2.dropdown.remove();
  445. select2.opts.element
  446. .removeData("select2")
  447. .unbind(".select2")
  448. .show();
  449. }
  450. },
  451. // abstract
  452. prepareOpts: function (opts) {
  453. var element, select, idKey;
  454. element = opts.element;
  455. if (element.get(0).tagName.toLowerCase() === "select") {
  456. this.select = select = opts.element;
  457. }
  458. if (select) {
  459. // these options are not allowed when attached to a select because they are picked up off the element itself
  460. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  461. if (this in opts) {
  462. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  463. }
  464. });
  465. }
  466. opts = $.extend({}, {
  467. containerCss: {},
  468. dropdownCss: {},
  469. containerCssClass: "",
  470. dropdownCssClass: "",
  471. populateResults: function(container, results, query) {
  472. var uidToData={}, populate, markup=[], uid, data, result, children, formatted;
  473. populate=function(results, depth) {
  474. var i, l, uid, result, selectable, compound;
  475. for (i = 0, l = results.length; i < l; i = i + 1) {
  476. result=results[i];
  477. selectable=("id" in result); // TODO switch to id() function
  478. compound=("children" in result) && result.children.length > 0;
  479. markup.push("<li class='select2-result-depth-"+depth);
  480. if (!selectable) { markup.push(" select2-result-unselectable"); } else { markup.push(" select2-result");}
  481. if (compound) { markup.push(" select2-result-with-children"); }
  482. markup.push("'");
  483. if (selectable) {
  484. uid=nextUid();
  485. markup.push(" id='select2-result-"+uid+"'");
  486. uidToData[uid]=result;
  487. }
  488. markup.push("><div class='select2-result-label'>");
  489. formatted=opts.formatResult(result, query, markup);
  490. // for backwards compat with <3.0 versions
  491. if (formatted!==undefined) {
  492. markup.push(formatted);
  493. }
  494. markup.push("</div>");
  495. if (compound) {
  496. markup.push("<ul class='select2-result-sub'>");
  497. populate(result.children, depth + 1);
  498. markup.push("</ul>");
  499. }
  500. markup.push("</li>");
  501. }
  502. };
  503. populate(results, 0);
  504. children=container.children();
  505. if (children.length===0) {
  506. container.html(markup.join(""));
  507. } else {
  508. $(children[children.length-1]).append(markup.join(""));
  509. }
  510. for (uid in uidToData) {
  511. $("#select2-result-"+uid, container).data("select2-data", uidToData[uid]);
  512. }
  513. },
  514. formatResult: function(result, query, markup) {
  515. markMatch(result.text, query.term, markup);
  516. },
  517. formatSelection: function (data) {
  518. return data.fullText || data.text;
  519. },
  520. formatNoMatches: function () { return "No matches found"; },
  521. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  522. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  523. minimumResultsForSearch: 0,
  524. minimumInputLength: 0,
  525. id: function (e) { return e.id; },
  526. matcher: function(term, text) {
  527. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  528. }
  529. }, opts);
  530. if (typeof(opts.id) !== "function") {
  531. idKey = opts.id;
  532. opts.id = function (e) { return e[idKey]; };
  533. }
  534. if (select) {
  535. opts.query = this.bind(function (query) {
  536. var data = { results: [], more: false },
  537. term = query.term,
  538. children, firstChild, process;
  539. process=function(element, collection) {
  540. var group;
  541. if (element.is("option")) {
  542. if (query.matcher(term, element.text())) {
  543. collection.push({id:element.attr("value"), text:element.text()});
  544. }
  545. } else if (element.is("optgroup")) {
  546. group={text:element.attr("label"), children:[]};
  547. element.children().each2(function(i, elm) { process(elm, group.children); });
  548. if (group.children.length>0) {
  549. collection.push(group);
  550. }
  551. }
  552. };
  553. children=element.children();
  554. // ignore the placeholder option if there is one
  555. if (this.getPlaceholder() !== undefined && children.length > 0) {
  556. firstChild = children[0];
  557. if ($(firstChild).text() === "") {
  558. children=children.not(firstChild);
  559. }
  560. }
  561. children.each2(function(i, elm) { process(elm, data.results); });
  562. query.callback(data);
  563. });
  564. // this is needed because inside val() we construct choices from options and there id is hardcoded
  565. opts.id=function(e) { return e.id; };
  566. } else {
  567. if (!("query" in opts)) {
  568. if ("ajax" in opts) {
  569. opts.query = ajax(opts.ajax);
  570. } else if ("data" in opts) {
  571. opts.query = local(opts.data);
  572. } else if ("tags" in opts) {
  573. opts.query = tags(opts.tags);
  574. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  575. opts.initSelection = function (element, callback) {
  576. var data = [];
  577. $(splitVal(element.val(), ",")).each(function () {
  578. data.push({id: this, text: this});
  579. });
  580. if ($.isFunction(callback))
  581. callback(data);
  582. };
  583. }
  584. }
  585. }
  586. if (typeof(opts.query) !== "function") {
  587. throw "query function not defined for Select2 " + opts.element.attr("id");
  588. }
  589. return opts;
  590. },
  591. /**
  592. * Monitor the original element for changes and update select2 accordingly
  593. */
  594. // abstract
  595. monitorSource: function () {
  596. this.opts.element.bind("change.select2", this.bind(function (e) {
  597. if (this.opts.element.data("select2-change-triggered") !== true) {
  598. this.initSelection();
  599. }
  600. }));
  601. },
  602. /**
  603. * Triggers the change event on the source element
  604. */
  605. // abstract
  606. triggerChange: function (details) {
  607. details = details || {};
  608. details= $.extend({}, details, { type: "change", val: this.val() });
  609. // prevents recursive triggering
  610. this.opts.element.data("select2-change-triggered", true);
  611. this.opts.element.trigger(details);
  612. this.opts.element.data("select2-change-triggered", false);
  613. },
  614. // abstract
  615. enable: function() {
  616. if (this.enabled) return;
  617. this.enabled=true;
  618. this.container.removeClass("select2-container-disabled");
  619. },
  620. // abstract
  621. disable: function() {
  622. if (!this.enabled) return;
  623. this.close();
  624. this.enabled=false;
  625. this.container.addClass("select2-container-disabled");
  626. },
  627. // abstract
  628. opened: function () {
  629. return this.container.hasClass("select2-dropdown-open");
  630. },
  631. // abstract
  632. positionDropdown: function() {
  633. var offset = this.container.offset();
  634. var height = this.container.outerHeight();
  635. var width = this.container.outerWidth();
  636. var css = {
  637. top: offset.top + height,
  638. left: offset.left,
  639. width: width
  640. }
  641. this.dropdown.css(css);
  642. },
  643. // abstract
  644. open: function () {
  645. if (this.opened()) return;
  646. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  647. if(this.dropdown[0] !== this.body.children().last()[0]) {
  648. // ensure the dropdown is the last child of body, so the z-index is always respected correctly
  649. this.dropdown.detach().appendTo(this.body);
  650. }
  651. this.dropdown.addClass("select2-drop-active");
  652. this.positionDropdown();
  653. this.updateResults(true);
  654. this.dropdown.show();
  655. this.ensureHighlightVisible();
  656. this.focusSearch();
  657. },
  658. // abstract
  659. close: function () {
  660. if (!this.opened()) return;
  661. this.dropdown.hide();
  662. this.container.removeClass("select2-dropdown-open");
  663. this.results.empty();
  664. this.clearSearch();
  665. },
  666. // abstract
  667. clearSearch: function () {
  668. },
  669. // abstract
  670. ensureHighlightVisible: function () {
  671. var results = this.results, children, index, child, hb, rb, y, more;
  672. index = this.highlight();
  673. if (index < 0) return;
  674. children = results.find(".select2-result");
  675. child = $(children[index]);
  676. hb = child.offset().top + child.outerHeight();
  677. // if this is the last child lets also make sure select2-more-results is visible
  678. if (index === children.length - 1) {
  679. more = results.find("li.select2-more-results");
  680. if (more.length > 0) {
  681. hb = more.offset().top + more.outerHeight();
  682. }
  683. }
  684. rb = results.offset().top + results.outerHeight();
  685. if (hb > rb) {
  686. results.scrollTop(results.scrollTop() + (hb - rb));
  687. }
  688. y = child.offset().top - results.offset().top;
  689. // make sure the top of the element is visible
  690. if (y < 0) {
  691. results.scrollTop(results.scrollTop() + y); // y is negative
  692. }
  693. },
  694. // abstract
  695. moveHighlight: function (delta) {
  696. var choices = this.results.find(".select2-result"),
  697. index = this.highlight();
  698. while (index > -1 && index < choices.length) {
  699. index += delta;
  700. if (!$(choices[index]).hasClass("select2-disabled")) {
  701. this.highlight(index);
  702. break;
  703. }
  704. }
  705. },
  706. // abstract
  707. highlight: function (index) {
  708. var choices = this.results.find(".select2-result .select2-result-label");
  709. if (arguments.length === 0) {
  710. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  711. }
  712. if (index >= choices.length) index = choices.length - 1;
  713. if (index < 0) index = 0;
  714. if ($(choices[index]).parent().is('.select2-result-unselectable')) {
  715. return;
  716. }
  717. choices.removeClass("select2-highlighted");
  718. $(choices[index]).addClass("select2-highlighted");
  719. this.ensureHighlightVisible();
  720. //if (this.opened()) this.focusSearch();
  721. },
  722. // abstract
  723. highlightUnderEvent: function (event) {
  724. var el = $(event.target).closest(".select2-result");
  725. if (el.length > 0 && !el.is(".select2-highlighted")) {
  726. var choices = this.results.find('.select2-result');
  727. this.highlight(choices.index(el));
  728. }
  729. },
  730. // abstract
  731. loadMoreIfNeeded: function () {
  732. var results = this.results,
  733. more = results.find("li.select2-more-results"),
  734. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  735. offset = -1, // index of first element without data
  736. page = this.resultsPage + 1,
  737. self=this,
  738. term=this.search.val(),
  739. context=this.context;
  740. if (more.length === 0) return;
  741. below = more.offset().top - results.offset().top - results.height();
  742. if (below <= 0) {
  743. more.addClass("select2-active");
  744. this.opts.query({
  745. term: term,
  746. page: page,
  747. context: context,
  748. matcher: this.opts.matcher,
  749. callback: this.bind(function (data) {
  750. self.opts.populateResults(results, data.results, {term: term, page: page, context:context});
  751. if (data.more===true) {
  752. more.detach();
  753. results.children().filter(":last").append(more);
  754. more.removeClass("select2-active");
  755. } else {
  756. more.remove();
  757. }
  758. self.resultsPage = page;
  759. })});
  760. }
  761. },
  762. /**
  763. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  764. */
  765. // abstract
  766. updateResults: function (initial) {
  767. var search = this.search, results = this.results, opts = this.opts, self=this;
  768. // if the search is currently hidden we do not alter the results
  769. if (initial !== true && this.showSearchInput === false) {
  770. return;
  771. }
  772. search.addClass("select2-active");
  773. function postRender() {
  774. results.scrollTop(0);
  775. search.removeClass("select2-active");
  776. }
  777. function render(html) {
  778. results.html(html);
  779. postRender();
  780. }
  781. if (search.val().length < opts.minimumInputLength) {
  782. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  783. return;
  784. }
  785. this.resultsPage = 1;
  786. opts.query({
  787. term: search.val(),
  788. page: this.resultsPage,
  789. context: null,
  790. matcher: opts.matcher,
  791. callback: this.bind(function (data) {
  792. var def; // default choice
  793. // save context, if any
  794. this.context = (data.context===undefined) ? null : data.context;
  795. // create a default choice and prepend it to the list
  796. if (this.opts.createSearchChoice && search.val() !== "") {
  797. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  798. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  799. if ($(data.results).filter(
  800. function () {
  801. return equal(self.id(this), self.id(def));
  802. }).length === 0) {
  803. data.results.unshift(def);
  804. }
  805. }
  806. }
  807. if (data.results.length === 0) {
  808. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  809. return;
  810. }
  811. results.empty();
  812. self.opts.populateResults(results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  813. postRender();
  814. if (data.more === true) {
  815. results.children().filter(":last").append("<li class='select2-more-results'>" + opts.formatLoadMore(this.resultsPage) + "</li>");
  816. }
  817. this.postprocessResults(data, initial);
  818. })});
  819. },
  820. // abstract
  821. cancel: function () {
  822. this.close();
  823. },
  824. // abstract
  825. blur: function () {
  826. this.close();
  827. this.container.removeClass("select2-container-active");
  828. this.dropdown.removeClass("select2-drop-active");
  829. if (this.search.is(":focus")) { this.search.blur(); }
  830. this.clearSearch();
  831. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  832. },
  833. // abstract
  834. focusSearch: function () {
  835. /* we do this in a timeout so that current event processing can complete before this code is executed.
  836. this makes sure the search field is focussed even if the current event would blur it */
  837. window.setTimeout(this.bind(function () {
  838. this.search.focus();
  839. }), 10);
  840. },
  841. // abstract
  842. selectHighlighted: function () {
  843. var data = this.results.find(".select2-highlighted").not(".select2-disabled").closest('.select2-result').not('.select2-result-unselectable').data("select2-data");
  844. if (data) {
  845. this.onSelect(data);
  846. }
  847. },
  848. // abstract
  849. getPlaceholder: function () {
  850. return this.opts.element.attr("placeholder") || this.opts.element.data("placeholder") || this.opts.placeholder;
  851. },
  852. /**
  853. * Get the desired width for the container element. This is
  854. * derived first from option `width` passed to select2, then
  855. * the inline 'style' on the original element, and finally
  856. * falls back to the jQuery calculated element width.
  857. *
  858. * @returns The width string (with units) for the container.
  859. */
  860. // abstract
  861. getContainerWidth: function () {
  862. var style, attrs, matches, i, l;
  863. if (this.opts.width !== undefined)
  864. return this.opts.width;
  865. style = this.opts.element.attr('style');
  866. if (style !== undefined) {
  867. attrs = style.split(';');
  868. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  869. matches = attrs[i].replace(/\s/g, '')
  870. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  871. if (matches !== null && matches.length >= 1)
  872. return matches[1];
  873. }
  874. }
  875. return this.opts.element.width() + 'px';
  876. }
  877. });
  878. SingleSelect2 = clazz(AbstractSelect2, {
  879. // single
  880. createContainer: function () {
  881. return $("<div></div>", {
  882. "class": "select2-container",
  883. "style": "width: " + this.getContainerWidth()
  884. }).html([
  885. " <a href='javascript:void(0)' class='select2-choice'><input type='text' class='select2-offscreen select2-focusser'/>",
  886. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  887. " <div><b></b></div>" ,
  888. "</a>",
  889. " <div class='select2-drop' style='display:none;'>" ,
  890. " <div class='select2-search'>" ,
  891. " <input type='text' autocomplete='off' class='select2-input'/>" ,
  892. " </div>" ,
  893. " <ul class='select2-results'>" ,
  894. " </ul>" ,
  895. "</div>"].join(""));
  896. },
  897. // single
  898. open: function () {
  899. if (this.opened()) return;
  900. this.parent.open.apply(this, arguments);
  901. },
  902. // single
  903. close: function () {
  904. if (!this.opened()) return;
  905. this.parent.close.apply(this, arguments);
  906. },
  907. // single
  908. focus: function () {
  909. this.close();
  910. this.selection.focus();
  911. },
  912. // single
  913. isFocused: function () {
  914. return this.selection.is(":focus");
  915. },
  916. // single
  917. cancel: function () {
  918. this.parent.cancel.apply(this, arguments);
  919. this.selection.focus();
  920. },
  921. // single
  922. initContainer: function () {
  923. var selection,
  924. container = this.container,
  925. dropdown = this.dropdown,
  926. containers = $([this.container.get(0), this.dropdown.get(0)]),
  927. clickingInside = false,
  928. selector = ".select2-choice",
  929. focusser=container.find("input.select2-focusser");
  930. this.selection = selection = container.find(selector);
  931. this.search.bind("keydown", this.bind(function (e) {
  932. switch (e.which) {
  933. case KEY.UP:
  934. case KEY.DOWN:
  935. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  936. killEvent(e);
  937. return;
  938. case KEY.TAB:
  939. case KEY.ENTER:
  940. this.selectHighlighted();
  941. killEvent(e);
  942. return;
  943. case KEY.ESC:
  944. this.cancel(e);
  945. killEvent(e);
  946. return;
  947. }
  948. }));
  949. containers.delegate(selector, "click", this.bind(function (e) {
  950. clickingInside = true;
  951. if (this.opened()) {
  952. this.close();
  953. selection.focus();
  954. } else if (this.enabled) {
  955. this.open();
  956. }
  957. e.preventDefault();
  958. clickingInside = false;
  959. }));
  960. containers.delegate(selector, "keydown", this.bind(function (e) {
  961. if (!this.enabled || e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  962. return;
  963. }
  964. this.open();
  965. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN || e.which === KEY.SPACE) {
  966. // prevent the page from scrolling
  967. killEvent(e);
  968. }
  969. if (e.which === KEY.ENTER) {
  970. // do not propagate the event otherwise we open, and propagate enter which closes
  971. killEvent(e);
  972. }
  973. }));
  974. containers.delegate(selector, "focus", function () { if (this.enabled) { containers.addClass("select2-container-active"); dropdown.addClass("select2-drop-active"); }});
  975. containers.delegate(selector, "blur", this.bind(function (e) {
  976. if (clickingInside) return;
  977. if (e.target===focusser.get(0)) return; // ignore blurs from focusser
  978. if (!this.opened()) { this.blur(); }
  979. }));
  980. selection.delegate("abbr", "click", this.bind(function (e) {
  981. if (!this.enabled) return;
  982. this.val("");
  983. killEvent(e);
  984. this.close();
  985. this.triggerChange();
  986. selection.focus();
  987. }));
  988. this.setPlaceholder();
  989. focusser.bind("focus", function() { selection.focus(); });
  990. selection.bind("focus", this.bind(function() {
  991. focusser.hide();
  992. this.container.addClass("select2-container-active");
  993. }));
  994. selection.bind("blur", function() { focusser.show(); });
  995. this.opts.element.bind("open", function() { focusser.hide(); });
  996. },
  997. /**
  998. * Sets selection based on source element's value
  999. */
  1000. // single
  1001. initSelection: function () {
  1002. var selected;
  1003. if (this.opts.element.val() === "") {
  1004. this.updateSelection({id: "", text: ""});
  1005. this.close();
  1006. this.setPlaceholder();
  1007. } else {
  1008. var self = this;
  1009. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1010. if (selected !== undefined && selected !== null) {
  1011. self.updateSelection(selected);
  1012. self.close();
  1013. self.setPlaceholder();
  1014. }
  1015. });
  1016. }
  1017. },
  1018. // single
  1019. prepareOpts: function () {
  1020. var opts = this.parent.prepareOpts.apply(this, arguments);
  1021. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1022. // install sthe selection initializer
  1023. opts.initSelection = function (element, callback) {
  1024. var selected = element.find(":selected");
  1025. // a single select box always has a value, no need to null check 'selected'
  1026. if ($.isFunction(callback))
  1027. callback({id: selected.attr("value"), text: selected.text()});
  1028. };
  1029. }
  1030. return opts;
  1031. },
  1032. // single
  1033. setPlaceholder: function () {
  1034. var placeholder = this.getPlaceholder();
  1035. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1036. // check for a first blank option if attached to a select
  1037. if (this.select && this.select.find("option:first").text() !== "") return;
  1038. if (typeof(placeholder) === "object") {
  1039. this.updateSelection(placeholder);
  1040. } else {
  1041. this.selection.find("span").html(placeholder);
  1042. }
  1043. this.selection.addClass("select2-default");
  1044. this.selection.find("abbr").hide();
  1045. }
  1046. },
  1047. // single
  1048. postprocessResults: function (data, initial) {
  1049. var selected = 0, self = this, showSearchInput = true;
  1050. // find the selected element in the result list
  1051. this.results.find(".select2-result").each2(function (i, elm) {
  1052. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1053. selected = i;
  1054. return false;
  1055. }
  1056. });
  1057. // and highlight it
  1058. this.highlight(selected);
  1059. // hide the search box if this is the first we got the results and there are a few of them
  1060. if (initial === true) {
  1061. // TODO below we use data.results.length, but what we really need is something recursive to calc the length
  1062. // TODO in case there are optgroups
  1063. showSearchInput = this.showSearchInput = data.results.length >= this.opts.minimumResultsForSearch;
  1064. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1065. //add "select2-with-searchbox" to the container if search box is shown
  1066. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1067. }
  1068. },
  1069. // single
  1070. onSelect: function (data) {
  1071. var old = this.opts.element.val();
  1072. this.opts.element.val(this.id(data));
  1073. this.updateSelection(data);
  1074. this.close();
  1075. this.selection.focus();
  1076. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1077. },
  1078. // single
  1079. updateSelection: function (data) {
  1080. this.selection
  1081. .find("span")
  1082. .html(this.opts.formatSelection(data));
  1083. this.selection.removeClass("select2-default");
  1084. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1085. this.selection.find("abbr").show();
  1086. }
  1087. },
  1088. // single
  1089. val: function () {
  1090. var val, data = null;
  1091. if (arguments.length === 0) {
  1092. return this.opts.element.val();
  1093. }
  1094. val = arguments[0];
  1095. if (this.select) {
  1096. // val is an id
  1097. this.select
  1098. .val(val)
  1099. .find(":selected").each2(function (i, elm) {
  1100. data = {id: elm.attr("value"), text: elm.text()};
  1101. return false;
  1102. });
  1103. this.updateSelection(data);
  1104. } else {
  1105. // val is an object. !val is true for [undefined,null,'']
  1106. this.opts.element.val(!val ? "" : this.id(val));
  1107. this.updateSelection(val);
  1108. }
  1109. this.setPlaceholder();
  1110. },
  1111. // single
  1112. clearSearch: function () {
  1113. this.search.val("");
  1114. }
  1115. });
  1116. MultiSelect2 = clazz(AbstractSelect2, {
  1117. // multi
  1118. createContainer: function () {
  1119. return $("<div></div>", {
  1120. "class": "select2-container select2-container-multi",
  1121. "style": "width: " + this.getContainerWidth()
  1122. }).html([
  1123. " <ul class='select2-choices'>",
  1124. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1125. " <li class='select2-search-field'>" ,
  1126. " <input type='text' autocomplete='off' style='width: 25px;' class='select2-input'>" ,
  1127. " </li>" ,
  1128. "</ul>" ,
  1129. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1130. " <ul class='select2-results'>" ,
  1131. " </ul>" ,
  1132. "</div>"].join(""));
  1133. },
  1134. // multi
  1135. prepareOpts: function () {
  1136. var opts = this.parent.prepareOpts.apply(this, arguments);
  1137. opts = $.extend({}, {
  1138. closeOnSelect: true
  1139. }, opts);
  1140. // TODO validate placeholder is a string if specified
  1141. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1142. // install sthe selection initializer
  1143. opts.initSelection = function (element,callback) {
  1144. var data = [];
  1145. element.find(":selected").each2(function (i, elm) {
  1146. data.push({id: elm.attr("value"), text: elm.text()});
  1147. });
  1148. if ($.isFunction(callback))
  1149. callback(data);
  1150. };
  1151. }
  1152. return opts;
  1153. },
  1154. // multi
  1155. initContainer: function () {
  1156. var selector = ".select2-choices", selection;
  1157. this.searchContainer = this.container.find(".select2-search-field");
  1158. this.selection = selection = this.container.find(selector);
  1159. this.search.bind("keydown", this.bind(function (e) {
  1160. if (!this.enabled) return;
  1161. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1162. this.close();
  1163. var choices,
  1164. selected = selection.find(".select2-search-choice-focus");
  1165. if (selected.length > 0) {
  1166. this.unselect(selected.first());
  1167. this.search.width(10);
  1168. killEvent(e);
  1169. return;
  1170. }
  1171. choices = selection.find(".select2-search-choice");
  1172. if (choices.length > 0) {
  1173. choices.last().addClass("select2-search-choice-focus");
  1174. }
  1175. } else {
  1176. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1177. }
  1178. if (this.opened()) {
  1179. switch (e.which) {
  1180. case KEY.UP:
  1181. case KEY.DOWN:
  1182. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1183. killEvent(e);
  1184. return;
  1185. case KEY.ENTER:
  1186. case KEY.TAB:
  1187. this.selectHighlighted();
  1188. killEvent(e);
  1189. return;
  1190. case KEY.ESC:
  1191. this.cancel(e);
  1192. killEvent(e);
  1193. return;
  1194. }
  1195. }
  1196. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1197. return;
  1198. }
  1199. this.open();
  1200. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1201. // prevent the page from scrolling
  1202. killEvent(e);
  1203. }
  1204. }));
  1205. this.search.bind("keyup", this.bind(this.resizeSearch));
  1206. this.container.delegate(selector, "click", this.bind(function (e) {
  1207. if (!this.enabled) return;
  1208. this.open();
  1209. this.focusSearch();
  1210. e.preventDefault();
  1211. }));
  1212. this.container.delegate(selector, "focus", this.bind(function () {
  1213. if (!this.enabled) return;
  1214. this.container.addClass("select2-container-active");
  1215. this.dropdown.addClass("select2-drop-active");
  1216. this.clearPlaceholder();
  1217. }));
  1218. // set the placeholder if necessary
  1219. this.clearSearch();
  1220. },
  1221. // multi
  1222. enable: function() {
  1223. if (this.enabled) return;
  1224. this.parent.enable.apply(this, arguments);
  1225. this.search.show();
  1226. },
  1227. // multi
  1228. disable: function() {
  1229. if (!this.enabled) return;
  1230. this.parent.disable.apply(this, arguments);
  1231. this.search.hide();
  1232. },
  1233. // multi
  1234. initSelection: function () {
  1235. var data;
  1236. if (this.opts.element.val() === "") {
  1237. this.updateSelection([]);
  1238. this.close();
  1239. // set the placeholder if necessary
  1240. this.clearSearch();
  1241. }
  1242. if (this.select || this.opts.element.val() !== "") {
  1243. var self = this;
  1244. this.opts.initSelection.call(null, this.opts.element, function(data){
  1245. if (data !== undefined && data !== null) {
  1246. self.updateSelection(data);
  1247. self.close();
  1248. // set the placeholder if necessary
  1249. self.clearSearch();
  1250. }
  1251. });
  1252. }
  1253. },
  1254. // multi
  1255. clearSearch: function () {
  1256. var placeholder = this.getPlaceholder();
  1257. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1258. this.search.val(placeholder).addClass("select2-default");
  1259. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1260. this.search.width(this.getContainerWidth());
  1261. } else {
  1262. this.search.val("").width(10);
  1263. }
  1264. },
  1265. // multi
  1266. clearPlaceholder: function () {
  1267. if (this.search.hasClass("select2-default")) {
  1268. this.search.val("").removeClass("select2-default");
  1269. }
  1270. },
  1271. // multi
  1272. open: function () {
  1273. if (this.opened()) return;
  1274. this.parent.open.apply(this, arguments);
  1275. this.clearPlaceholder();
  1276. this.resizeSearch();
  1277. this.focusSearch();
  1278. },
  1279. // multi
  1280. close: function () {
  1281. if (!this.opened()) return;
  1282. this.parent.close.apply(this, arguments);
  1283. },
  1284. // multi
  1285. focus: function () {
  1286. this.close();
  1287. this.search.focus();
  1288. },
  1289. // multi
  1290. isFocused: function () {
  1291. return this.search.hasClass("select2-focused");
  1292. },
  1293. // multi
  1294. updateSelection: function (data) {
  1295. var ids = [], filtered = [], self = this;
  1296. // filter out duplicates
  1297. $(data).each(function () {
  1298. if (indexOf(self.id(this), ids) < 0) {
  1299. ids.push(self.id(this));
  1300. filtered.push(this);
  1301. }
  1302. });
  1303. data = filtered;
  1304. this.selection.find(".select2-search-choice").remove();
  1305. $(data).each(function () {
  1306. self.addSelectedChoice(this);
  1307. });
  1308. self.postprocessResults();
  1309. },
  1310. // multi
  1311. onSelect: function (data) {
  1312. this.addSelectedChoice(data);
  1313. if (this.select) { this.postprocessResults(); }
  1314. if (this.opts.closeOnSelect) {
  1315. this.close();
  1316. this.search.width(10);
  1317. } else {
  1318. this.search.width(10);
  1319. this.resizeSearch();
  1320. }
  1321. // since its not possible to select an element that has already been
  1322. // added we do not need to check if this is a new element before firing change
  1323. this.triggerChange({ added: data });
  1324. this.focusSearch();
  1325. },
  1326. // multi
  1327. cancel: function () {
  1328. this.close();
  1329. this.focusSearch();
  1330. },
  1331. // multi
  1332. addSelectedChoice: function (data) {
  1333. var choice,
  1334. id = this.id(data),
  1335. parts,
  1336. val = this.getVal();
  1337. parts = ["<li class='select2-search-choice'>",
  1338. this.opts.formatSelection(data),
  1339. "<a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>",
  1340. "</li>"
  1341. ];
  1342. choice = $(parts.join(""));
  1343. choice.find("a")
  1344. .bind("click dblclick", this.bind(function (e) {
  1345. if (!this.enabled) return;
  1346. this.unselect($(e.target));
  1347. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1348. killEvent(e);
  1349. this.close();
  1350. this.focusSearch();
  1351. })).bind("focus", this.bind(function () {
  1352. if (!this.enabled) return;
  1353. this.container.addClass("select2-container-active");
  1354. this.dropdown.addClass("select2-drop-active");
  1355. }));
  1356. choice.data("select2-data", data);
  1357. choice.insertBefore(this.searchContainer);
  1358. val.push(id);
  1359. this.setVal(val);
  1360. },
  1361. // multi
  1362. unselect: function (selected) {
  1363. var val = this.getVal(),
  1364. data,
  1365. index;
  1366. selected = selected.closest(".select2-search-choice");
  1367. if (selected.length === 0) {
  1368. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1369. }
  1370. data = selected.data("select2-data");
  1371. index = indexOf(this.id(data), val);
  1372. if (index >= 0) {
  1373. val.splice(index, 1);
  1374. this.setVal(val);
  1375. if (this.select) this.postprocessResults();
  1376. }
  1377. selected.remove();
  1378. this.triggerChange({ removed: data });
  1379. },
  1380. // multi
  1381. postprocessResults: function () {
  1382. var val = this.getVal(),
  1383. choices = this.results.find(".select2-result"),
  1384. self = this;
  1385. choices.each2(function (i, choice) {
  1386. var id = self.id(choice.data("select2-data"));
  1387. if (indexOf(id, val) >= 0) {
  1388. choice.addClass("select2-disabled");
  1389. } else {
  1390. choice.removeClass("select2-disabled");
  1391. }
  1392. });
  1393. choices.each2(function (i, choice) {
  1394. if (!choice.hasClass("select2-disabled")) {
  1395. self.highlight(i);
  1396. return false;
  1397. }
  1398. });
  1399. },
  1400. // multi
  1401. resizeSearch: function () {
  1402. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  1403. sideBorderPadding = getSideBorderPadding(this.search);
  1404. minimumWidth = measureTextWidth(this.search) + 10;
  1405. left = this.search.offset().left;
  1406. maxWidth = this.selection.width();
  1407. containerLeft = this.selection.offset().left;
  1408. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  1409. if (searchWidth < minimumWidth) {
  1410. searchWidth = maxWidth - sideBorderPadding;
  1411. }
  1412. if (searchWidth < 40) {
  1413. searchWidth = maxWidth - sideBorderPadding;
  1414. }
  1415. this.search.width(searchWidth);
  1416. },
  1417. // multi
  1418. getVal: function () {
  1419. var val;
  1420. if (this.select) {
  1421. val = this.select.val();
  1422. return val === null ? [] : val;
  1423. } else {
  1424. val = this.opts.element.val();
  1425. return splitVal(val, ",");
  1426. }
  1427. },
  1428. // multi
  1429. setVal: function (val) {
  1430. var unique;
  1431. if (this.select) {
  1432. this.select.val(val);
  1433. } else {
  1434. unique = [];
  1435. // filter out duplicates
  1436. $(val).each(function () {
  1437. if (indexOf(this, unique) < 0) unique.push(this);
  1438. });
  1439. this.opts.element.val(unique.length === 0 ? "" : unique.join(","));
  1440. }
  1441. },
  1442. // multi
  1443. val: function () {
  1444. var val, data = [], self=this;
  1445. if (arguments.length === 0) {
  1446. return this.getVal();
  1447. }
  1448. val = arguments[0];
  1449. if (this.select) {
  1450. // val is a list of ids
  1451. this.setVal(val);
  1452. this.select.find(":selected").each(function () {
  1453. data.push({id: $(this).attr("value"), text: $(this).text()});
  1454. });
  1455. this.updateSelection(data);
  1456. } else {
  1457. val = (val === null) ? [] : val;
  1458. this.setVal(val);
  1459. // val is a list of objects
  1460. $(val).each(function () { data.push(self.id(this)); });
  1461. this.setVal(data);
  1462. this.updateSelection(val);
  1463. }
  1464. this.clearSearch();
  1465. },
  1466. // multi
  1467. onSortStart: function() {
  1468. if (this.select) {
  1469. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  1470. }
  1471. // collapse search field into 0 width so its container can be collapsed as well
  1472. this.search.width(0);
  1473. // hide the container
  1474. this.searchContainer.hide();
  1475. },
  1476. // multi
  1477. onSortEnd:function() {
  1478. var val=[], self=this;
  1479. // show search and move it to the end of the list
  1480. this.searchContainer.show();
  1481. // make sure the search container is the last item in the list
  1482. this.searchContainer.appendTo(this.searchContainer.parent());
  1483. // since we collapsed the width in dragStarteed, we resize it here
  1484. this.resizeSearch();
  1485. // update selection
  1486. this.selection.find(".select2-search-choice").each(function() {
  1487. val.push(self.opts.id($(this).data("select2-data")));
  1488. });
  1489. this.setVal(val);
  1490. this.triggerChange();
  1491. }
  1492. });
  1493. $.fn.select2 = function () {
  1494. var args = Array.prototype.slice.call(arguments, 0),
  1495. opts,
  1496. select2,
  1497. value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown"];
  1498. this.each(function () {
  1499. if (args.length === 0 || typeof(args[0]) === "object") {
  1500. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1501. opts.element = $(this);
  1502. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1503. multiple = opts.element.attr("multiple");
  1504. } else {
  1505. multiple = opts.multiple || false;
  1506. if ("tags" in opts) {opts.multiple = multiple = true;}
  1507. }
  1508. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1509. select2.init(opts);
  1510. } else if (typeof(args[0]) === "string") {
  1511. if (indexOf(args[0], allowedMethods) < 0) {
  1512. throw "Unknown method: " + args[0];
  1513. }
  1514. value = undefined;
  1515. select2 = $(this).data("select2");
  1516. if (select2 === undefined) return;
  1517. if (args[0] === "container") {
  1518. value=select2.container;
  1519. } else {
  1520. value = select2[args[0]].apply(select2, args.slice(1));
  1521. }
  1522. if (value !== undefined) {return false;}
  1523. } else {
  1524. throw "Invalid arguments to select2 plugin: " + args;
  1525. }
  1526. });
  1527. return (value === undefined) ? this : value;
  1528. };
  1529. // exports
  1530. window.Select2 = {
  1531. query: {
  1532. ajax: ajax,
  1533. local: local,
  1534. tags: tags
  1535. }, util: {
  1536. debounce: debounce,
  1537. markMatch: markMatch
  1538. }, "class": {
  1539. "abstract": AbstractSelect2,
  1540. "single": SingleSelect2,
  1541. "multi": MultiSelect2
  1542. }
  1543. };
  1544. }(jQuery));