select2.js 71 KB

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