select2.js 73 KB

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