select2.js 71 KB

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