select2.js 71 KB

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