select2.js 67 KB

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