select2.js 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017
  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 focusin 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");
  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 || !this.opened())) {
  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. // position dropdown before making a potentially long request
  846. this.positionDropdown();
  847. this.resultsPage = 1;
  848. opts.query({
  849. term: search.val(),
  850. page: this.resultsPage,
  851. context: null,
  852. matcher: opts.matcher,
  853. callback: this.bind(function (data) {
  854. var def; // default choice
  855. // save context, if any
  856. this.context = (data.context===undefined) ? null : data.context;
  857. // create a default choice and prepend it to the list
  858. if (this.opts.createSearchChoice && search.val() !== "") {
  859. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  860. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  861. if ($(data.results).filter(
  862. function () {
  863. return equal(self.id(this), self.id(def));
  864. }).length === 0) {
  865. data.results.unshift(def);
  866. }
  867. }
  868. }
  869. if (data.results.length === 0) {
  870. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  871. return;
  872. }
  873. results.empty();
  874. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  875. if (data.more === true) {
  876. results.children().filter(":last").append("<li class='select2-more-results'>" + opts.formatLoadMore(this.resultsPage) + "</li>");
  877. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  878. }
  879. this.postprocessResults(data, initial);
  880. postRender();
  881. })});
  882. },
  883. // abstract
  884. cancel: function () {
  885. this.close();
  886. },
  887. // abstract
  888. blur: function () {
  889. this.close();
  890. this.container.removeClass("select2-container-active");
  891. this.dropdown.removeClass("select2-drop-active");
  892. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  893. if (this.search[0] === document.activeElement) { this.search.blur(); }
  894. this.clearSearch();
  895. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  896. },
  897. // abstract
  898. focusSearch: function () {
  899. /* we do this in a timeout so that current event processing can complete before this code is executed.
  900. this makes sure the search field is focussed even if the current event would blur it */
  901. window.setTimeout(this.bind(function () {
  902. this.search.focus();
  903. }), 10);
  904. },
  905. // abstract
  906. selectHighlighted: function () {
  907. var data = this.results.find(".select2-highlighted").not(".select2-disabled").closest('.select2-result-selectable').data("select2-data");
  908. if (data) {
  909. this.onSelect(data);
  910. }
  911. },
  912. // abstract
  913. getPlaceholder: function () {
  914. return this.opts.element.attr("placeholder") ||
  915. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  916. this.opts.element.data("placeholder") ||
  917. this.opts.placeholder;
  918. },
  919. /**
  920. * Get the desired width for the container element. This is
  921. * derived first from option `width` passed to select2, then
  922. * the inline 'style' on the original element, and finally
  923. * falls back to the jQuery calculated element width.
  924. *
  925. * @returns The width string (with units) for the container.
  926. */
  927. // abstract
  928. getContainerWidth: function () {
  929. var style, attrs, matches, i, l;
  930. // see if there is width specified in opts
  931. if (this.opts.width !== undefined)
  932. return this.opts.width;
  933. // next check if there is inline style on the element that contains width
  934. style = this.opts.element.attr('style');
  935. if (style !== undefined) {
  936. attrs = style.split(';');
  937. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  938. matches = attrs[i].replace(/\s/g, '')
  939. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  940. if (matches !== null && matches.length >= 1)
  941. return matches[1];
  942. }
  943. }
  944. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  945. // when attached to input type=hidden or elements hidden via css
  946. style = this.opts.element.css('width');
  947. if (style.indexOf("%") > 0) return style;
  948. // finally, fallback on the calculated width of the element
  949. return (this.opts.element.width() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px');
  950. }
  951. });
  952. SingleSelect2 = clazz(AbstractSelect2, {
  953. // single
  954. createContainer: function () {
  955. return $("<div></div>", {
  956. "class": "select2-container",
  957. "style": "width: " + this.getContainerWidth()
  958. }).html([
  959. " <a href='javascript:void(0)' class='select2-choice'>",
  960. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  961. " <div><b></b></div>" ,
  962. "</a>",
  963. " <div class='select2-drop select2-offscreen'>" ,
  964. " <div class='select2-search'>" ,
  965. " <input type='text' autocomplete='off' class='select2-input'/>" ,
  966. " </div>" ,
  967. " <ul class='select2-results'>" ,
  968. " </ul>" ,
  969. "</div>"].join(""));
  970. },
  971. // single
  972. opening: function () {
  973. this.parent.opening.apply(this, arguments);
  974. this.dropdown.removeClass("select2-offscreen");
  975. },
  976. // single
  977. close: function () {
  978. if (!this.opened()) return;
  979. this.parent.close.apply(this, arguments);
  980. this.dropdown.removeAttr("style").addClass("select2-offscreen").insertAfter(this.selection).show();
  981. },
  982. // single
  983. focus: function () {
  984. this.close();
  985. this.search.focus();
  986. },
  987. // single
  988. isFocused: function () {
  989. return this.selection[0] === document.activeElement;
  990. },
  991. // single
  992. cancel: function () {
  993. this.parent.cancel.apply(this, arguments);
  994. this.search.focus();
  995. },
  996. // single
  997. initContainer: function () {
  998. var selection,
  999. container = this.container,
  1000. dropdown = this.dropdown,
  1001. clickingInside = false;
  1002. this.selection = selection = container.find(".select2-choice");
  1003. this.search.bind("keydown", this.bind(function (e) {
  1004. if (!this.enabled) return;
  1005. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN || e.which === KEY.SPACE) {
  1006. // prevent the page from scrolling
  1007. killEvent(e);
  1008. return;
  1009. }
  1010. if (this.opened()) {
  1011. switch (e.which) {
  1012. case KEY.UP:
  1013. case KEY.DOWN:
  1014. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1015. killEvent(e);
  1016. return;
  1017. case KEY.TAB:
  1018. case KEY.ENTER:
  1019. this.selectHighlighted();
  1020. killEvent(e);
  1021. return;
  1022. case KEY.ESC:
  1023. this.cancel(e);
  1024. killEvent(e);
  1025. return;
  1026. }
  1027. } else {
  1028. if (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.ENTER) {
  1033. // do not propagate the event otherwise we open, and propagate enter which closes
  1034. killEvent(e);
  1035. return;
  1036. }
  1037. }
  1038. }));
  1039. selection.bind("click", this.bind(function (e) {
  1040. clickingInside = true;
  1041. if (this.opened()) {
  1042. this.close();
  1043. this.search.focus();
  1044. } else if (this.enabled) {
  1045. this.open();
  1046. }
  1047. killEvent(e);
  1048. clickingInside = false;
  1049. }));
  1050. dropdown.bind("click", this.bind(function() { this.search.focus(); }));
  1051. selection.delegate("abbr", "click", this.bind(function (e) {
  1052. if (!this.enabled) return;
  1053. this.clear();
  1054. killEvent(e);
  1055. this.close();
  1056. this.triggerChange();
  1057. this.search.focus();
  1058. }));
  1059. selection.bind("focus", this.bind(function() { this.search.focus(); }));
  1060. this.setPlaceholder();
  1061. this.search.bind("focus", this.bind(function() {
  1062. this.container.addClass("select2-container-active");
  1063. }));
  1064. },
  1065. clear: function() {
  1066. this.opts.element.val("");
  1067. this.selection.find("span").empty();
  1068. this.selection.removeData("select2-data");
  1069. this.setPlaceholder();
  1070. },
  1071. /**
  1072. * Sets selection based on source element's value
  1073. */
  1074. // single
  1075. initSelection: function () {
  1076. var selected;
  1077. if (this.opts.element.val() === "") {
  1078. this.updateSelection({id: "", text: ""});
  1079. this.close();
  1080. this.setPlaceholder();
  1081. } else {
  1082. var self = this;
  1083. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1084. if (selected !== undefined && selected !== null) {
  1085. self.updateSelection(selected);
  1086. self.close();
  1087. self.setPlaceholder();
  1088. }
  1089. });
  1090. }
  1091. },
  1092. // single
  1093. prepareOpts: function () {
  1094. var opts = this.parent.prepareOpts.apply(this, arguments);
  1095. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1096. // install the selection initializer
  1097. opts.initSelection = function (element, callback) {
  1098. var selected = element.find(":selected");
  1099. // a single select box always has a value, no need to null check 'selected'
  1100. if ($.isFunction(callback))
  1101. callback({id: selected.attr("value"), text: selected.text()});
  1102. };
  1103. }
  1104. return opts;
  1105. },
  1106. // single
  1107. setPlaceholder: function () {
  1108. var placeholder = this.getPlaceholder();
  1109. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1110. // check for a first blank option if attached to a select
  1111. if (this.select && this.select.find("option:first").text() !== "") return;
  1112. if (typeof(placeholder) === "object") {
  1113. this.updateSelection(placeholder);
  1114. } else {
  1115. this.selection.find("span").html(placeholder);
  1116. }
  1117. this.selection.addClass("select2-default");
  1118. this.selection.find("abbr").hide();
  1119. }
  1120. },
  1121. // single
  1122. postprocessResults: function (data, initial) {
  1123. var selected = 0, self = this, showSearchInput = true;
  1124. // find the selected element in the result list
  1125. this.results.find(".select2-result-selectable").each2(function (i, elm) {
  1126. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1127. selected = i;
  1128. return false;
  1129. }
  1130. });
  1131. // and highlight it
  1132. this.highlight(selected);
  1133. // hide the search box if this is the first we got the results and there are a few of them
  1134. if (initial === true) {
  1135. // TODO below we use data.results.length, but what we really need is something recursive to calc the length
  1136. // TODO in case there are optgroups
  1137. showSearchInput = this.showSearchInput = data.results.length >= this.opts.minimumResultsForSearch;
  1138. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1139. //add "select2-with-searchbox" to the container if search box is shown
  1140. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1141. }
  1142. },
  1143. // single
  1144. onSelect: function (data) {
  1145. var old = this.opts.element.val();
  1146. this.opts.element.val(this.id(data));
  1147. this.updateSelection(data);
  1148. this.close();
  1149. this.search.focus();
  1150. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1151. },
  1152. // single
  1153. updateSelection: function (data) {
  1154. var container=this.selection.find("span"), formatted;
  1155. this.selection.data("select2-data", data);
  1156. container.empty();
  1157. formatted=this.opts.formatSelection(data, container);
  1158. if (formatted !== undefined) {
  1159. container.append(formatted);
  1160. }
  1161. this.selection.removeClass("select2-default");
  1162. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1163. this.selection.find("abbr").show();
  1164. }
  1165. },
  1166. // single
  1167. val: function () {
  1168. var val, data = null;
  1169. if (arguments.length === 0) {
  1170. return this.opts.element.val();
  1171. }
  1172. val = arguments[0];
  1173. if (this.select) {
  1174. // val is an id
  1175. this.select
  1176. .val(val)
  1177. .find(":selected").each2(function (i, elm) {
  1178. data = {id: elm.attr("value"), text: elm.text()};
  1179. return false;
  1180. });
  1181. this.updateSelection(data);
  1182. } else {
  1183. // val is an object. !val is true for [undefined,null,'']
  1184. this.opts.element.val(!val ? "" : this.id(val));
  1185. this.updateSelection(val);
  1186. }
  1187. this.setPlaceholder();
  1188. },
  1189. // single
  1190. clearSearch: function () {
  1191. this.search.val("");
  1192. },
  1193. // single
  1194. data: function(value) {
  1195. if (arguments.length === 0) {
  1196. return this.selection.data("select2-data");
  1197. } else {
  1198. if (!value || value === "") {
  1199. this.clear();
  1200. } else {
  1201. this.opts.element.val(!value ? "" : this.id(value));
  1202. this.updateSelection(value);
  1203. }
  1204. }
  1205. }
  1206. });
  1207. MultiSelect2 = clazz(AbstractSelect2, {
  1208. // multi
  1209. createContainer: function () {
  1210. return $("<div></div>", {
  1211. "class": "select2-container select2-container-multi",
  1212. "style": "width: " + this.getContainerWidth()
  1213. }).html([
  1214. " <ul class='select2-choices'>",
  1215. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1216. " <li class='select2-search-field'>" ,
  1217. " <input type='text' autocomplete='off' style='width: 25px;' class='select2-input'>" ,
  1218. " </li>" ,
  1219. "</ul>" ,
  1220. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1221. " <ul class='select2-results'>" ,
  1222. " </ul>" ,
  1223. "</div>"].join(""));
  1224. },
  1225. // multi
  1226. prepareOpts: function () {
  1227. var opts = this.parent.prepareOpts.apply(this, arguments);
  1228. opts = $.extend({}, {
  1229. closeOnSelect: true
  1230. }, opts);
  1231. // TODO validate placeholder is a string if specified
  1232. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1233. // install sthe selection initializer
  1234. opts.initSelection = function (element,callback) {
  1235. var data = [];
  1236. element.find(":selected").each2(function (i, elm) {
  1237. data.push({id: elm.attr("value"), text: elm.text()});
  1238. });
  1239. if ($.isFunction(callback))
  1240. callback(data);
  1241. };
  1242. }
  1243. return opts;
  1244. },
  1245. // multi
  1246. initContainer: function () {
  1247. var selector = ".select2-choices", selection;
  1248. this.searchContainer = this.container.find(".select2-search-field");
  1249. this.selection = selection = this.container.find(selector);
  1250. this.search.bind("keydown", this.bind(function (e) {
  1251. if (!this.enabled) return;
  1252. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1253. this.close();
  1254. var choices,
  1255. selected = selection.find(".select2-search-choice-focus");
  1256. if (selected.length > 0) {
  1257. this.unselect(selected.first());
  1258. this.search.width(10);
  1259. killEvent(e);
  1260. return;
  1261. }
  1262. choices = selection.find(".select2-search-choice");
  1263. if (choices.length > 0) {
  1264. choices.last().addClass("select2-search-choice-focus");
  1265. }
  1266. } else {
  1267. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1268. }
  1269. if (this.opened()) {
  1270. switch (e.which) {
  1271. case KEY.UP:
  1272. case KEY.DOWN:
  1273. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1274. killEvent(e);
  1275. return;
  1276. case KEY.ENTER:
  1277. case KEY.TAB:
  1278. this.selectHighlighted();
  1279. killEvent(e);
  1280. return;
  1281. case KEY.ESC:
  1282. this.cancel(e);
  1283. killEvent(e);
  1284. return;
  1285. }
  1286. }
  1287. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1288. return;
  1289. }
  1290. this.open();
  1291. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1292. // prevent the page from scrolling
  1293. killEvent(e);
  1294. }
  1295. }));
  1296. this.search.bind("keyup", this.bind(this.resizeSearch));
  1297. this.container.delegate(selector, "click", this.bind(function (e) {
  1298. if (!this.enabled) return;
  1299. this.clearPlaceholder();
  1300. this.open();
  1301. this.focusSearch();
  1302. e.preventDefault();
  1303. }));
  1304. this.container.delegate(selector, "focus", this.bind(function () {
  1305. if (!this.enabled) return;
  1306. this.container.addClass("select2-container-active");
  1307. this.dropdown.addClass("select2-drop-active");
  1308. this.clearPlaceholder();
  1309. }));
  1310. // set the placeholder if necessary
  1311. this.clearSearch();
  1312. },
  1313. // multi
  1314. enable: function() {
  1315. if (this.enabled) return;
  1316. this.parent.enable.apply(this, arguments);
  1317. this.search.show();
  1318. },
  1319. // multi
  1320. disable: function() {
  1321. if (!this.enabled) return;
  1322. this.parent.disable.apply(this, arguments);
  1323. this.search.hide();
  1324. },
  1325. // multi
  1326. initSelection: function () {
  1327. var data;
  1328. if (this.opts.element.val() === "") {
  1329. this.updateSelection([]);
  1330. this.close();
  1331. // set the placeholder if necessary
  1332. this.clearSearch();
  1333. }
  1334. if (this.select || this.opts.element.val() !== "") {
  1335. var self = this;
  1336. this.opts.initSelection.call(null, this.opts.element, function(data){
  1337. if (data !== undefined && data !== null) {
  1338. self.updateSelection(data);
  1339. self.close();
  1340. // set the placeholder if necessary
  1341. self.clearSearch();
  1342. }
  1343. });
  1344. }
  1345. },
  1346. // multi
  1347. clearSearch: function () {
  1348. var placeholder = this.getPlaceholder();
  1349. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1350. this.search.val(placeholder).addClass("select2-default");
  1351. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1352. this.resizeSearch();
  1353. } else {
  1354. // we set this to " " instead of "" and later clear it on focus() because there is a firefox bug
  1355. // that does not properly render the caret when the field starts out blank
  1356. this.search.val(" ").width(10);
  1357. }
  1358. },
  1359. // multi
  1360. clearPlaceholder: function () {
  1361. if (this.search.hasClass("select2-default")) {
  1362. this.search.val("").removeClass("select2-default");
  1363. } else {
  1364. // work around for the space character we set to avoid firefox caret bug
  1365. if (this.search.val() === " ") this.search.val("");
  1366. }
  1367. },
  1368. // multi
  1369. opening: function () {
  1370. this.parent.opening.apply(this, arguments);
  1371. this.clearPlaceholder();
  1372. this.resizeSearch();
  1373. this.focusSearch();
  1374. },
  1375. // multi
  1376. close: function () {
  1377. if (!this.opened()) return;
  1378. this.parent.close.apply(this, arguments);
  1379. },
  1380. // multi
  1381. focus: function () {
  1382. this.close();
  1383. this.search.focus();
  1384. },
  1385. // multi
  1386. isFocused: function () {
  1387. return this.search.hasClass("select2-focused");
  1388. },
  1389. // multi
  1390. updateSelection: function (data) {
  1391. var ids = [], filtered = [], self = this;
  1392. // filter out duplicates
  1393. $(data).each(function () {
  1394. if (indexOf(self.id(this), ids) < 0) {
  1395. ids.push(self.id(this));
  1396. filtered.push(this);
  1397. }
  1398. });
  1399. data = filtered;
  1400. this.selection.find(".select2-search-choice").remove();
  1401. $(data).each(function () {
  1402. self.addSelectedChoice(this);
  1403. });
  1404. self.postprocessResults();
  1405. },
  1406. // multi
  1407. onSelect: function (data) {
  1408. this.addSelectedChoice(data);
  1409. if (this.select) { this.postprocessResults(); }
  1410. if (this.opts.closeOnSelect) {
  1411. this.close();
  1412. this.search.width(10);
  1413. } else {
  1414. this.search.width(10);
  1415. this.resizeSearch();
  1416. }
  1417. // since its not possible to select an element that has already been
  1418. // added we do not need to check if this is a new element before firing change
  1419. this.triggerChange({ added: data });
  1420. this.focusSearch();
  1421. },
  1422. // multi
  1423. cancel: function () {
  1424. this.close();
  1425. this.focusSearch();
  1426. },
  1427. // multi
  1428. addSelectedChoice: function (data) {
  1429. var choice=$("<li class='select2-search-choice'></li>"),
  1430. id = this.id(data),
  1431. val = this.getVal(),
  1432. formatted;
  1433. choice.find('.select2-tmp').replaceWith(this.opts.formatSelection(data));
  1434. formatted=this.opts.formatSelection(data, choice);
  1435. if (formatted !== undefined) {
  1436. choice.append(formatted);
  1437. }
  1438. choice.append("<a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>");
  1439. choice.find(".select2-search-choice-close")
  1440. .bind("click dblclick", this.bind(function (e) {
  1441. if (!this.enabled) return;
  1442. $(e.target).closest(".select2-search-choice").fadeOut('fast').animate({width: "hide"}, 50, this.bind(function(){
  1443. this.unselect($(e.target));
  1444. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1445. this.close();
  1446. this.focusSearch();
  1447. })).dequeue();
  1448. killEvent(e);
  1449. })).bind("focus", this.bind(function () {
  1450. if (!this.enabled) return;
  1451. this.container.addClass("select2-container-active");
  1452. this.dropdown.addClass("select2-drop-active");
  1453. }));
  1454. choice.data("select2-data", data);
  1455. choice.insertBefore(this.searchContainer);
  1456. val.push(id);
  1457. this.setVal(val);
  1458. },
  1459. // multi
  1460. unselect: function (selected) {
  1461. var val = this.getVal(),
  1462. data,
  1463. index;
  1464. selected = selected.closest(".select2-search-choice");
  1465. if (selected.length === 0) {
  1466. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1467. }
  1468. data = selected.data("select2-data");
  1469. index = indexOf(this.id(data), val);
  1470. if (index >= 0) {
  1471. val.splice(index, 1);
  1472. this.setVal(val);
  1473. if (this.select) this.postprocessResults();
  1474. }
  1475. selected.remove();
  1476. this.triggerChange({ removed: data });
  1477. },
  1478. // multi
  1479. postprocessResults: function () {
  1480. var val = this.getVal(),
  1481. choices = this.results.find(".select2-result-selectable"),
  1482. self = this;
  1483. choices.each2(function (i, choice) {
  1484. var id = self.id(choice.data("select2-data"));
  1485. if (indexOf(id, val) >= 0) {
  1486. choice.addClass("select2-disabled");
  1487. } else {
  1488. choice.removeClass("select2-disabled");
  1489. }
  1490. });
  1491. choices.each2(function (i, choice) {
  1492. if (!choice.hasClass("select2-disabled")) {
  1493. self.highlight(i);
  1494. return false;
  1495. }
  1496. });
  1497. },
  1498. // multi
  1499. resizeSearch: function () {
  1500. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  1501. sideBorderPadding = getSideBorderPadding(this.search);
  1502. minimumWidth = measureTextWidth(this.search) + 10;
  1503. left = this.search.offset().left;
  1504. maxWidth = this.selection.width();
  1505. containerLeft = this.selection.offset().left;
  1506. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  1507. if (searchWidth < minimumWidth) {
  1508. searchWidth = maxWidth - sideBorderPadding;
  1509. }
  1510. if (searchWidth < 40) {
  1511. searchWidth = maxWidth - sideBorderPadding;
  1512. }
  1513. this.search.width(searchWidth);
  1514. },
  1515. // multi
  1516. getVal: function () {
  1517. var val;
  1518. if (this.select) {
  1519. val = this.select.val();
  1520. return val === null ? [] : val;
  1521. } else {
  1522. val = this.opts.element.val();
  1523. return splitVal(val, this.opts.separator);
  1524. }
  1525. },
  1526. // multi
  1527. setVal: function (val) {
  1528. var unique;
  1529. if (this.select) {
  1530. this.select.val(val);
  1531. } else {
  1532. unique = [];
  1533. // filter out duplicates
  1534. $(val).each(function () {
  1535. if (indexOf(this, unique) < 0) unique.push(this);
  1536. });
  1537. this.opts.element.val(unique.length === 0 ? "" : unique.join(","));
  1538. }
  1539. },
  1540. // multi
  1541. val: function () {
  1542. var val, data = [], self=this;
  1543. if (arguments.length === 0) {
  1544. return this.getVal();
  1545. }
  1546. val = arguments[0];
  1547. if (this.select) {
  1548. // val is a list of ids
  1549. this.setVal(val);
  1550. this.select.find(":selected").each(function () {
  1551. data.push({id: $(this).attr("value"), text: $(this).text()});
  1552. });
  1553. this.updateSelection(data);
  1554. } else {
  1555. val = (val === null) ? [] : val;
  1556. // val is a list of objects
  1557. $(val).each(function () { data.push(self.id(this)); });
  1558. this.setVal(data);
  1559. this.updateSelection(val);
  1560. }
  1561. this.clearSearch();
  1562. },
  1563. // multi
  1564. onSortStart: function() {
  1565. if (this.select) {
  1566. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  1567. }
  1568. // collapse search field into 0 width so its container can be collapsed as well
  1569. this.search.width(0);
  1570. // hide the container
  1571. this.searchContainer.hide();
  1572. },
  1573. // multi
  1574. onSortEnd:function() {
  1575. var val=[], self=this;
  1576. // show search and move it to the end of the list
  1577. this.searchContainer.show();
  1578. // make sure the search container is the last item in the list
  1579. this.searchContainer.appendTo(this.searchContainer.parent());
  1580. // since we collapsed the width in dragStarted, we resize it here
  1581. this.resizeSearch();
  1582. // update selection
  1583. this.selection.find(".select2-search-choice").each(function() {
  1584. val.push(self.opts.id($(this).data("select2-data")));
  1585. });
  1586. this.setVal(val);
  1587. this.triggerChange();
  1588. },
  1589. // multi
  1590. data: function(values) {
  1591. var self=this, ids;
  1592. if (arguments.length === 0) {
  1593. return this.selection
  1594. .find(".select2-search-choice")
  1595. .map(function() { return $(this).data("select2-data"); })
  1596. .get();
  1597. } else {
  1598. ids = $.map(values, function(e) { return self.opts.id(e)});
  1599. this.setVal(ids);
  1600. this.updateSelection(values);
  1601. this.clearSearch();
  1602. }
  1603. }
  1604. });
  1605. $.fn.select2 = function () {
  1606. var args = Array.prototype.slice.call(arguments, 0),
  1607. opts,
  1608. select2,
  1609. value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
  1610. this.each(function () {
  1611. if (args.length === 0 || typeof(args[0]) === "object") {
  1612. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1613. opts.element = $(this);
  1614. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1615. multiple = opts.element.attr("multiple");
  1616. } else {
  1617. multiple = opts.multiple || false;
  1618. if ("tags" in opts) {opts.multiple = multiple = true;}
  1619. }
  1620. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1621. select2.init(opts);
  1622. } else if (typeof(args[0]) === "string") {
  1623. if (indexOf(args[0], allowedMethods) < 0) {
  1624. throw "Unknown method: " + args[0];
  1625. }
  1626. value = undefined;
  1627. select2 = $(this).data("select2");
  1628. if (select2 === undefined) return;
  1629. if (args[0] === "container") {
  1630. value=select2.container;
  1631. } else {
  1632. value = select2[args[0]].apply(select2, args.slice(1));
  1633. }
  1634. if (value !== undefined) {return false;}
  1635. } else {
  1636. throw "Invalid arguments to select2 plugin: " + args;
  1637. }
  1638. });
  1639. return (value === undefined) ? this : value;
  1640. };
  1641. // plugin defaults, accessible to users
  1642. $.fn.select2.defaults = {
  1643. containerCss: {},
  1644. dropdownCss: {},
  1645. containerCssClass: "",
  1646. dropdownCssClass: "",
  1647. formatResult: function(result, container, query) {
  1648. var markup=[];
  1649. markMatch(result.text, query.term, markup);
  1650. return markup.join("");
  1651. },
  1652. formatSelection: function (data, container) {
  1653. return data.text;
  1654. },
  1655. formatNoMatches: function () { return "No matches found"; },
  1656. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  1657. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  1658. minimumResultsForSearch: 0,
  1659. minimumInputLength: 0,
  1660. id: function (e) { return e.id; },
  1661. matcher: function(term, text) {
  1662. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  1663. }
  1664. };
  1665. // exports
  1666. window.Select2 = {
  1667. query: {
  1668. ajax: ajax,
  1669. local: local,
  1670. tags: tags
  1671. }, util: {
  1672. debounce: debounce,
  1673. markMatch: markMatch
  1674. }, "class": {
  1675. "abstract": AbstractSelect2,
  1676. "single": SingleSelect2,
  1677. "multi": MultiSelect2
  1678. }
  1679. };
  1680. }(jQuery));