select2.js 70 KB

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