select2.js 68 KB

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