select2.js 80 KB

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