select2.js 72 KB

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