select2.js 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  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");});
  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: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. if (!selectable) { markup.push(" select2-result-unselectable"); } else { markup.push(" select2-result");}
  482. if (compound) { markup.push(" select2-result-with-children"); }
  483. markup.push("'");
  484. if (selectable) {
  485. uid=nextUid();
  486. markup.push(" id='select2-result-"+uid+"'");
  487. uidToData[uid]=result;
  488. }
  489. markup.push("><div class='select2-result-label'>");
  490. formatted=opts.formatResult(result, query, markup);
  491. // for backwards compat with <3.0 versions
  492. if (formatted!==undefined) {
  493. markup.push(formatted);
  494. }
  495. markup.push("</div>");
  496. if (compound) {
  497. markup.push("<ul class='select2-result-sub'>");
  498. populate(result.children, depth + 1);
  499. markup.push("</ul>");
  500. }
  501. markup.push("</li>");
  502. }
  503. };
  504. populate(results, 0);
  505. container.append(markup.join(""));
  506. for (uid in uidToData) {
  507. $("#select2-result-"+uid, container).data("select2-data", uidToData[uid]);
  508. }
  509. },
  510. formatResult: function(result, query, markup) {
  511. markMatch(result.text, query.term, markup);
  512. },
  513. formatSelection: function (data) {
  514. return data.fullText || data.text;
  515. },
  516. formatNoMatches: function () { return "No matches found"; },
  517. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  518. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  519. minimumResultsForSearch: 0,
  520. minimumInputLength: 0,
  521. id: function (e) { return e.id; },
  522. matcher: function(term, text) {
  523. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  524. }
  525. }, opts);
  526. if (typeof(opts.id) !== "function") {
  527. idKey = opts.id;
  528. opts.id = function (e) { return e[idKey]; };
  529. }
  530. if (select) {
  531. opts.query = this.bind(function (query) {
  532. var data = { results: [], more: false },
  533. term = query.term,
  534. children, firstChild, process;
  535. process=function(element, collection) {
  536. var group;
  537. if (element.is("option")) {
  538. if (query.matcher(term, element.text())) {
  539. collection.push({id:element.attr("value"), text:element.text(), element: element.get()});
  540. }
  541. } else if (element.is("optgroup")) {
  542. group={text:element.attr("label"), children:[], element: element.get()};
  543. element.children().each2(function(i, elm) { process(elm, group.children); });
  544. if (group.children.length>0) {
  545. collection.push(group);
  546. }
  547. }
  548. };
  549. children=element.children();
  550. // ignore the placeholder option if there is one
  551. if (this.getPlaceholder() !== undefined && children.length > 0) {
  552. firstChild = children[0];
  553. if ($(firstChild).text() === "") {
  554. children=children.not(firstChild);
  555. }
  556. }
  557. children.each2(function(i, elm) { process(elm, data.results); });
  558. query.callback(data);
  559. });
  560. // this is needed because inside val() we construct choices from options and there id is hardcoded
  561. opts.id=function(e) { return e.id; };
  562. } else {
  563. if (!("query" in opts)) {
  564. if ("ajax" in opts) {
  565. opts.query = ajax(opts.ajax);
  566. } else if ("data" in opts) {
  567. opts.query = local(opts.data);
  568. } else if ("tags" in opts) {
  569. opts.query = tags(opts.tags);
  570. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  571. opts.initSelection = function (element, callback) {
  572. var data = [];
  573. $(splitVal(element.val(), ",")).each(function () {
  574. data.push({id: this, text: this});
  575. });
  576. callback(data);
  577. };
  578. }
  579. }
  580. }
  581. if (typeof(opts.query) !== "function") {
  582. throw "query function not defined for Select2 " + opts.element.attr("id");
  583. }
  584. return opts;
  585. },
  586. /**
  587. * Monitor the original element for changes and update select2 accordingly
  588. */
  589. // abstract
  590. monitorSource: function () {
  591. this.opts.element.bind("change.select2", this.bind(function (e) {
  592. if (this.opts.element.data("select2-change-triggered") !== true) {
  593. this.initSelection();
  594. }
  595. }));
  596. },
  597. /**
  598. * Triggers the change event on the source element
  599. */
  600. // abstract
  601. triggerChange: function (details) {
  602. details = details || {};
  603. details= $.extend({}, details, { type: "change", val: this.val() });
  604. // prevents recursive triggering
  605. this.opts.element.data("select2-change-triggered", true);
  606. this.opts.element.trigger(details);
  607. this.opts.element.data("select2-change-triggered", false);
  608. },
  609. // abstract
  610. enable: function() {
  611. if (this.enabled) return;
  612. this.enabled=true;
  613. this.container.removeClass("select2-container-disabled");
  614. },
  615. // abstract
  616. disable: function() {
  617. if (!this.enabled) return;
  618. this.close();
  619. this.enabled=false;
  620. this.container.addClass("select2-container-disabled");
  621. },
  622. // abstract
  623. opened: function () {
  624. return this.container.hasClass("select2-dropdown-open");
  625. },
  626. // abstract
  627. positionDropdown: function() {
  628. var offset = this.container.offset();
  629. var height = this.container.outerHeight();
  630. var width = this.container.outerWidth();
  631. var css = {
  632. top: offset.top + height,
  633. left: offset.left,
  634. width: width
  635. }
  636. this.dropdown.css(css);
  637. },
  638. // abstract
  639. open: function () {
  640. if (this.opened()) return;
  641. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  642. if(this.dropdown[0] !== this.body.children().last()[0]) {
  643. // ensure the dropdown is the last child of body, so the z-index is always respected correctly
  644. this.dropdown.detach().appendTo(this.body);
  645. }
  646. this.dropdown.addClass("select2-drop-active");
  647. this.positionDropdown();
  648. this.updateResults(true);
  649. this.dropdown.show();
  650. this.ensureHighlightVisible();
  651. this.focusSearch();
  652. },
  653. // abstract
  654. close: function () {
  655. if (!this.opened()) return;
  656. this.dropdown.hide();
  657. this.container.removeClass("select2-dropdown-open");
  658. this.results.empty();
  659. this.clearSearch();
  660. },
  661. // abstract
  662. clearSearch: function () {
  663. },
  664. // abstract
  665. ensureHighlightVisible: function () {
  666. var results = this.results, children, index, child, hb, rb, y, more;
  667. index = this.highlight();
  668. if (index < 0) return;
  669. children = results.find(".select2-result");
  670. child = $(children[index]);
  671. hb = child.offset().top + child.outerHeight();
  672. // if this is the last child lets also make sure select2-more-results is visible
  673. if (index === children.length - 1) {
  674. more = results.find("li.select2-more-results");
  675. if (more.length > 0) {
  676. hb = more.offset().top + more.outerHeight();
  677. }
  678. }
  679. rb = results.offset().top + results.outerHeight();
  680. if (hb > rb) {
  681. results.scrollTop(results.scrollTop() + (hb - rb));
  682. }
  683. y = child.offset().top - results.offset().top;
  684. // make sure the top of the element is visible
  685. if (y < 0) {
  686. results.scrollTop(results.scrollTop() + y); // y is negative
  687. }
  688. },
  689. // abstract
  690. moveHighlight: function (delta) {
  691. var choices = this.results.find(".select2-result"),
  692. index = this.highlight();
  693. while (index > -1 && index < choices.length) {
  694. index += delta;
  695. if (!$(choices[index]).hasClass("select2-disabled")) {
  696. this.highlight(index);
  697. break;
  698. }
  699. }
  700. },
  701. // abstract
  702. highlight: function (index) {
  703. var choices = this.results.find(".select2-result .select2-result-label");
  704. if (arguments.length === 0) {
  705. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  706. }
  707. if (index >= choices.length) index = choices.length - 1;
  708. if (index < 0) index = 0;
  709. if ($(choices[index]).parent().is('.select2-result-unselectable')) {
  710. return;
  711. }
  712. choices.removeClass("select2-highlighted");
  713. $(choices[index]).addClass("select2-highlighted");
  714. this.ensureHighlightVisible();
  715. //if (this.opened()) this.focusSearch();
  716. },
  717. // abstract
  718. highlightUnderEvent: function (event) {
  719. var el = $(event.target).closest(".select2-result");
  720. if (el.length > 0 && !el.is(".select2-highlighted")) {
  721. var choices = this.results.find('.select2-result');
  722. this.highlight(choices.index(el));
  723. }
  724. },
  725. // abstract
  726. loadMoreIfNeeded: function () {
  727. var results = this.results,
  728. more = results.find("li.select2-more-results"),
  729. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  730. offset = -1, // index of first element without data
  731. page = this.resultsPage + 1,
  732. self=this,
  733. term=this.search.val(),
  734. context=this.context;
  735. if (more.length === 0) return;
  736. below = more.offset().top - results.offset().top - results.height();
  737. if (below <= 0) {
  738. more.addClass("select2-active");
  739. this.opts.query({
  740. term: term,
  741. page: page,
  742. context: context,
  743. matcher: this.opts.matcher,
  744. callback: this.bind(function (data) {
  745. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  746. if (data.more===true) {
  747. more.detach().appendTo(results.children(":last")).text(self.opts.formatLoadMore(page+1));
  748. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  749. } else {
  750. more.remove();
  751. }
  752. self.resultsPage = page;
  753. })});
  754. }
  755. },
  756. /**
  757. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  758. */
  759. // abstract
  760. updateResults: function (initial) {
  761. var search = this.search, results = this.results, opts = this.opts, self=this;
  762. // if the search is currently hidden we do not alter the results
  763. if (initial !== true && this.showSearchInput === false) {
  764. return;
  765. }
  766. search.addClass("select2-active");
  767. function postRender() {
  768. results.scrollTop(0);
  769. search.removeClass("select2-active");
  770. }
  771. function render(html) {
  772. results.html(html);
  773. postRender();
  774. }
  775. if (search.val().length < opts.minimumInputLength) {
  776. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  777. return;
  778. }
  779. this.resultsPage = 1;
  780. opts.query({
  781. term: search.val(),
  782. page: this.resultsPage,
  783. context: null,
  784. matcher: opts.matcher,
  785. callback: this.bind(function (data) {
  786. var def; // default choice
  787. // save context, if any
  788. this.context = (data.context===undefined) ? null : data.context;
  789. // create a default choice and prepend it to the list
  790. if (this.opts.createSearchChoice && search.val() !== "") {
  791. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  792. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  793. if ($(data.results).filter(
  794. function () {
  795. return equal(self.id(this), self.id(def));
  796. }).length === 0) {
  797. data.results.unshift(def);
  798. }
  799. }
  800. }
  801. if (data.results.length === 0) {
  802. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  803. return;
  804. }
  805. results.empty();
  806. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  807. postRender();
  808. if (data.more === true) {
  809. results.children().filter(":last").append("<li class='select2-more-results'>" + opts.formatLoadMore(this.resultsPage) + "</li>");
  810. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  811. }
  812. this.postprocessResults(data, initial);
  813. })});
  814. },
  815. // abstract
  816. cancel: function () {
  817. this.close();
  818. },
  819. // abstract
  820. blur: function () {
  821. this.close();
  822. this.container.removeClass("select2-container-active");
  823. this.dropdown.removeClass("select2-drop-active");
  824. if (this.search.is(":focus")) { this.search.blur(); }
  825. this.clearSearch();
  826. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  827. },
  828. // abstract
  829. focusSearch: function () {
  830. /* we do this in a timeout so that current event processing can complete before this code is executed.
  831. this makes sure the search field is focussed even if the current event would blur it */
  832. window.setTimeout(this.bind(function () {
  833. this.search.focus();
  834. }), 10);
  835. },
  836. // abstract
  837. selectHighlighted: function () {
  838. var data = this.results.find(".select2-highlighted").not(".select2-disabled").closest('.select2-result').not('.select2-result-unselectable').data("select2-data");
  839. if (data) {
  840. this.onSelect(data);
  841. }
  842. },
  843. // abstract
  844. getPlaceholder: function () {
  845. return this.opts.element.attr("placeholder") ||
  846. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  847. this.opts.element.data("placeholder") ||
  848. this.opts.placeholder;
  849. },
  850. /**
  851. * Get the desired width for the container element. This is
  852. * derived first from option `width` passed to select2, then
  853. * the inline 'style' on the original element, and finally
  854. * falls back to the jQuery calculated element width.
  855. *
  856. * @returns The width string (with units) for the container.
  857. */
  858. // abstract
  859. getContainerWidth: function () {
  860. var style, attrs, matches, i, l;
  861. if (this.opts.width !== undefined)
  862. return this.opts.width;
  863. style = this.opts.element.attr('style');
  864. if (style !== undefined) {
  865. attrs = style.split(';');
  866. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  867. matches = attrs[i].replace(/\s/g, '')
  868. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  869. if (matches !== null && matches.length >= 1)
  870. return matches[1];
  871. }
  872. }
  873. return this.opts.element.width() + 'px';
  874. }
  875. });
  876. SingleSelect2 = clazz(AbstractSelect2, {
  877. // single
  878. createContainer: function () {
  879. return $("<div></div>", {
  880. "class": "select2-container",
  881. "style": "width: " + this.getContainerWidth()
  882. }).html([
  883. " <a href='javascript:void(0)' class='select2-choice'><input type='text' class='select2-offscreen select2-focusser'/>",
  884. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  885. " <div><b></b></div>" ,
  886. "</a>",
  887. " <div class='select2-drop' style='display:none;'>" ,
  888. " <div class='select2-search'>" ,
  889. " <input type='text' autocomplete='off' class='select2-input'/>" ,
  890. " </div>" ,
  891. " <ul class='select2-results'>" ,
  892. " </ul>" ,
  893. "</div>"].join(""));
  894. },
  895. // single
  896. open: function () {
  897. if (this.opened()) return;
  898. this.parent.open.apply(this, arguments);
  899. },
  900. // single
  901. close: function () {
  902. if (!this.opened()) return;
  903. this.parent.close.apply(this, arguments);
  904. },
  905. // single
  906. focus: function () {
  907. this.close();
  908. this.selection.focus();
  909. },
  910. // single
  911. isFocused: function () {
  912. return this.selection.is(":focus");
  913. },
  914. // single
  915. cancel: function () {
  916. this.parent.cancel.apply(this, arguments);
  917. this.selection.focus();
  918. },
  919. // single
  920. initContainer: function () {
  921. var selection,
  922. container = this.container,
  923. dropdown = this.dropdown,
  924. containers = $([this.container.get(0), this.dropdown.get(0)]),
  925. clickingInside = false,
  926. selector = ".select2-choice",
  927. focusser=container.find("input.select2-focusser");
  928. this.selection = selection = container.find(selector);
  929. this.search.bind("keydown", this.bind(function (e) {
  930. switch (e.which) {
  931. case KEY.UP:
  932. case KEY.DOWN:
  933. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  934. killEvent(e);
  935. return;
  936. case KEY.TAB:
  937. case KEY.ENTER:
  938. this.selectHighlighted();
  939. killEvent(e);
  940. return;
  941. case KEY.ESC:
  942. this.cancel(e);
  943. killEvent(e);
  944. return;
  945. }
  946. }));
  947. containers.delegate(selector, "click", this.bind(function (e) {
  948. clickingInside = true;
  949. if (this.opened()) {
  950. this.close();
  951. selection.focus();
  952. } else if (this.enabled) {
  953. this.open();
  954. }
  955. e.preventDefault();
  956. clickingInside = false;
  957. }));
  958. containers.delegate(selector, "keydown", this.bind(function (e) {
  959. if (!this.enabled || e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  960. return;
  961. }
  962. this.open();
  963. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN || e.which === KEY.SPACE) {
  964. // prevent the page from scrolling
  965. killEvent(e);
  966. }
  967. if (e.which === KEY.ENTER) {
  968. // do not propagate the event otherwise we open, and propagate enter which closes
  969. killEvent(e);
  970. }
  971. }));
  972. containers.delegate(selector, "focus", function () { if (this.enabled) { containers.addClass("select2-container-active"); dropdown.addClass("select2-drop-active"); }});
  973. containers.delegate(selector, "blur", this.bind(function (e) {
  974. if (clickingInside) return;
  975. if (e.target===focusser.get(0)) return; // ignore blurs from focusser
  976. if (!this.opened()) { this.blur(); }
  977. }));
  978. selection.delegate("abbr", "click", this.bind(function (e) {
  979. if (!this.enabled) return;
  980. this.clear();
  981. killEvent(e);
  982. this.close();
  983. this.triggerChange();
  984. selection.focus();
  985. }));
  986. this.setPlaceholder();
  987. focusser.bind("focus", function() { selection.focus(); });
  988. selection.bind("focus", this.bind(function() {
  989. focusser.hide();
  990. this.container.addClass("select2-container-active");
  991. }));
  992. selection.bind("blur", function() { focusser.show(); });
  993. this.opts.element.bind("open", function() { focusser.hide(); });
  994. },
  995. clear: function() {
  996. this.opts.element.val("");
  997. this.selection.find("span").empty();
  998. this.selection.removeData("select2-data");
  999. this.setPlaceholder();
  1000. },
  1001. /**
  1002. * Sets selection based on source element's value
  1003. */
  1004. // single
  1005. initSelection: function () {
  1006. var selected;
  1007. if (this.opts.element.val() === "") {
  1008. this.updateSelection({id: "", text: ""});
  1009. this.close();
  1010. this.setPlaceholder();
  1011. } else {
  1012. var self = this;
  1013. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1014. if (selected !== undefined && selected !== null) {
  1015. self.updateSelection(selected);
  1016. self.close();
  1017. self.setPlaceholder();
  1018. }
  1019. });
  1020. }
  1021. },
  1022. // single
  1023. prepareOpts: function () {
  1024. var opts = this.parent.prepareOpts.apply(this, arguments);
  1025. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1026. // install the selection initializer
  1027. opts.initSelection = function (element, callback) {
  1028. var selected = element.find(":selected");
  1029. // a single select box always has a value, no need to null check 'selected'
  1030. if ($.isFunction(callback))
  1031. callback({id: selected.attr("value"), text: selected.text()});
  1032. };
  1033. }
  1034. return opts;
  1035. },
  1036. // single
  1037. setPlaceholder: function () {
  1038. var placeholder = this.getPlaceholder();
  1039. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1040. // check for a first blank option if attached to a select
  1041. if (this.select && this.select.find("option:first").text() !== "") return;
  1042. if (typeof(placeholder) === "object") {
  1043. this.updateSelection(placeholder);
  1044. } else {
  1045. this.selection.find("span").html(placeholder);
  1046. }
  1047. this.selection.addClass("select2-default");
  1048. this.selection.find("abbr").hide();
  1049. }
  1050. },
  1051. // single
  1052. postprocessResults: function (data, initial) {
  1053. var selected = 0, self = this, showSearchInput = true;
  1054. // find the selected element in the result list
  1055. this.results.find(".select2-result").each2(function (i, elm) {
  1056. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1057. selected = i;
  1058. return false;
  1059. }
  1060. });
  1061. // and highlight it
  1062. this.highlight(selected);
  1063. // hide the search box if this is the first we got the results and there are a few of them
  1064. if (initial === true) {
  1065. // TODO below we use data.results.length, but what we really need is something recursive to calc the length
  1066. // TODO in case there are optgroups
  1067. showSearchInput = this.showSearchInput = data.results.length >= this.opts.minimumResultsForSearch;
  1068. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1069. //add "select2-with-searchbox" to the container if search box is shown
  1070. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1071. }
  1072. },
  1073. // single
  1074. onSelect: function (data) {
  1075. var old = this.opts.element.val();
  1076. this.opts.element.val(this.id(data));
  1077. this.updateSelection(data);
  1078. this.close();
  1079. this.selection.focus();
  1080. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1081. },
  1082. // single
  1083. updateSelection: function (data) {
  1084. this.selection.data("select2-data", data);
  1085. this.selection
  1086. .find("span")
  1087. .html(this.opts.formatSelection(data));
  1088. this.selection.removeClass("select2-default");
  1089. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1090. this.selection.find("abbr").show();
  1091. }
  1092. },
  1093. // single
  1094. val: function () {
  1095. var val, data = null;
  1096. if (arguments.length === 0) {
  1097. return this.opts.element.val();
  1098. }
  1099. val = arguments[0];
  1100. if (this.select) {
  1101. // val is an id
  1102. this.select
  1103. .val(val)
  1104. .find(":selected").each2(function (i, elm) {
  1105. data = {id: elm.attr("value"), text: elm.text()};
  1106. return false;
  1107. });
  1108. this.updateSelection(data);
  1109. } else {
  1110. // val is an object. !val is true for [undefined,null,'']
  1111. this.opts.element.val(!val ? "" : this.id(val));
  1112. this.updateSelection(val);
  1113. }
  1114. this.setPlaceholder();
  1115. },
  1116. // single
  1117. clearSearch: function () {
  1118. this.search.val("");
  1119. },
  1120. // single
  1121. data: function(value) {
  1122. if (arguments.length === 0) {
  1123. return this.selection.data("select2-data");
  1124. } else {
  1125. if (!value || value === "") {
  1126. this.clear();
  1127. } else {
  1128. this.opts.element.val(!value ? "" : this.id(value));
  1129. this.updateSelection(value);
  1130. }
  1131. }
  1132. }
  1133. });
  1134. MultiSelect2 = clazz(AbstractSelect2, {
  1135. // multi
  1136. createContainer: function () {
  1137. return $("<div></div>", {
  1138. "class": "select2-container select2-container-multi",
  1139. "style": "width: " + this.getContainerWidth()
  1140. }).html([
  1141. " <ul class='select2-choices'>",
  1142. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1143. " <li class='select2-search-field'>" ,
  1144. " <input type='text' autocomplete='off' style='width: 25px;' class='select2-input'>" ,
  1145. " </li>" ,
  1146. "</ul>" ,
  1147. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1148. " <ul class='select2-results'>" ,
  1149. " </ul>" ,
  1150. "</div>"].join(""));
  1151. },
  1152. // multi
  1153. prepareOpts: function () {
  1154. var opts = this.parent.prepareOpts.apply(this, arguments);
  1155. opts = $.extend({}, {
  1156. closeOnSelect: true
  1157. }, opts);
  1158. // TODO validate placeholder is a string if specified
  1159. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1160. // install sthe selection initializer
  1161. opts.initSelection = function (element,callback) {
  1162. var data = [];
  1163. element.find(":selected").each2(function (i, elm) {
  1164. data.push({id: elm.attr("value"), text: elm.text()});
  1165. });
  1166. if ($.isFunction(callback))
  1167. callback(data);
  1168. };
  1169. }
  1170. return opts;
  1171. },
  1172. // multi
  1173. initContainer: function () {
  1174. var selector = ".select2-choices", selection;
  1175. this.searchContainer = this.container.find(".select2-search-field");
  1176. this.selection = selection = this.container.find(selector);
  1177. this.search.bind("keydown", this.bind(function (e) {
  1178. if (!this.enabled) return;
  1179. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1180. this.close();
  1181. var choices,
  1182. selected = selection.find(".select2-search-choice-focus");
  1183. if (selected.length > 0) {
  1184. this.unselect(selected.first());
  1185. this.search.width(10);
  1186. killEvent(e);
  1187. return;
  1188. }
  1189. choices = selection.find(".select2-search-choice");
  1190. if (choices.length > 0) {
  1191. choices.last().addClass("select2-search-choice-focus");
  1192. }
  1193. } else {
  1194. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1195. }
  1196. if (this.opened()) {
  1197. switch (e.which) {
  1198. case KEY.UP:
  1199. case KEY.DOWN:
  1200. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1201. killEvent(e);
  1202. return;
  1203. case KEY.ENTER:
  1204. case KEY.TAB:
  1205. this.selectHighlighted();
  1206. killEvent(e);
  1207. return;
  1208. case KEY.ESC:
  1209. this.cancel(e);
  1210. killEvent(e);
  1211. return;
  1212. }
  1213. }
  1214. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1215. return;
  1216. }
  1217. this.open();
  1218. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1219. // prevent the page from scrolling
  1220. killEvent(e);
  1221. }
  1222. }));
  1223. this.search.bind("keyup", this.bind(this.resizeSearch));
  1224. this.container.delegate(selector, "click", this.bind(function (e) {
  1225. if (!this.enabled) return;
  1226. this.open();
  1227. this.focusSearch();
  1228. e.preventDefault();
  1229. }));
  1230. this.container.delegate(selector, "focus", this.bind(function () {
  1231. if (!this.enabled) return;
  1232. this.container.addClass("select2-container-active");
  1233. this.dropdown.addClass("select2-drop-active");
  1234. this.clearPlaceholder();
  1235. }));
  1236. // set the placeholder if necessary
  1237. this.clearSearch();
  1238. },
  1239. // multi
  1240. enable: function() {
  1241. if (this.enabled) return;
  1242. this.parent.enable.apply(this, arguments);
  1243. this.search.show();
  1244. },
  1245. // multi
  1246. disable: function() {
  1247. if (!this.enabled) return;
  1248. this.parent.disable.apply(this, arguments);
  1249. this.search.hide();
  1250. },
  1251. // multi
  1252. initSelection: function () {
  1253. var data;
  1254. if (this.opts.element.val() === "") {
  1255. this.updateSelection([]);
  1256. this.close();
  1257. // set the placeholder if necessary
  1258. this.clearSearch();
  1259. }
  1260. if (this.select || this.opts.element.val() !== "") {
  1261. var self = this;
  1262. this.opts.initSelection.call(null, this.opts.element, function(data){
  1263. if (data !== undefined && data !== null) {
  1264. self.updateSelection(data);
  1265. self.close();
  1266. // set the placeholder if necessary
  1267. self.clearSearch();
  1268. }
  1269. });
  1270. }
  1271. },
  1272. // multi
  1273. clearSearch: function () {
  1274. var placeholder = this.getPlaceholder();
  1275. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1276. this.search.val(placeholder).addClass("select2-default");
  1277. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1278. this.search.width(this.getContainerWidth());
  1279. } else {
  1280. this.search.val("").width(10);
  1281. }
  1282. },
  1283. // multi
  1284. clearPlaceholder: function () {
  1285. if (this.search.hasClass("select2-default")) {
  1286. this.search.val("").removeClass("select2-default");
  1287. }
  1288. },
  1289. // multi
  1290. open: function () {
  1291. if (this.opened()) return;
  1292. this.parent.open.apply(this, arguments);
  1293. this.clearPlaceholder();
  1294. this.resizeSearch();
  1295. this.focusSearch();
  1296. },
  1297. // multi
  1298. close: function () {
  1299. if (!this.opened()) return;
  1300. this.parent.close.apply(this, arguments);
  1301. },
  1302. // multi
  1303. focus: function () {
  1304. this.close();
  1305. this.search.focus();
  1306. },
  1307. // multi
  1308. isFocused: function () {
  1309. return this.search.hasClass("select2-focused");
  1310. },
  1311. // multi
  1312. updateSelection: function (data) {
  1313. var ids = [], filtered = [], self = this;
  1314. // filter out duplicates
  1315. $(data).each(function () {
  1316. if (indexOf(self.id(this), ids) < 0) {
  1317. ids.push(self.id(this));
  1318. filtered.push(this);
  1319. }
  1320. });
  1321. data = filtered;
  1322. this.selection.find(".select2-search-choice").remove();
  1323. $(data).each(function () {
  1324. self.addSelectedChoice(this);
  1325. });
  1326. self.postprocessResults();
  1327. },
  1328. // multi
  1329. onSelect: function (data) {
  1330. this.addSelectedChoice(data);
  1331. if (this.select) { this.postprocessResults(); }
  1332. if (this.opts.closeOnSelect) {
  1333. this.close();
  1334. this.search.width(10);
  1335. } else {
  1336. this.search.width(10);
  1337. this.resizeSearch();
  1338. }
  1339. // since its not possible to select an element that has already been
  1340. // added we do not need to check if this is a new element before firing change
  1341. this.triggerChange({ added: data });
  1342. this.focusSearch();
  1343. },
  1344. // multi
  1345. cancel: function () {
  1346. this.close();
  1347. this.focusSearch();
  1348. },
  1349. // multi
  1350. addSelectedChoice: function (data) {
  1351. var choice,
  1352. id = this.id(data),
  1353. parts,
  1354. val = this.getVal();
  1355. parts = ["<li class='select2-search-choice'>",
  1356. this.opts.formatSelection(data),
  1357. "<a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>",
  1358. "</li>"
  1359. ];
  1360. choice = $(parts.join(""));
  1361. choice.find("a")
  1362. .bind("click dblclick", this.bind(function (e) {
  1363. if (!this.enabled) return;
  1364. this.unselect($(e.target));
  1365. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1366. killEvent(e);
  1367. this.close();
  1368. this.focusSearch();
  1369. })).bind("focus", this.bind(function () {
  1370. if (!this.enabled) return;
  1371. this.container.addClass("select2-container-active");
  1372. this.dropdown.addClass("select2-drop-active");
  1373. }));
  1374. choice.data("select2-data", data);
  1375. choice.insertBefore(this.searchContainer);
  1376. val.push(id);
  1377. this.setVal(val);
  1378. },
  1379. // multi
  1380. unselect: function (selected) {
  1381. var val = this.getVal(),
  1382. data,
  1383. index;
  1384. selected = selected.closest(".select2-search-choice");
  1385. if (selected.length === 0) {
  1386. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1387. }
  1388. data = selected.data("select2-data");
  1389. index = indexOf(this.id(data), val);
  1390. if (index >= 0) {
  1391. val.splice(index, 1);
  1392. this.setVal(val);
  1393. if (this.select) this.postprocessResults();
  1394. }
  1395. selected.remove();
  1396. this.triggerChange({ removed: data });
  1397. },
  1398. // multi
  1399. postprocessResults: function () {
  1400. var val = this.getVal(),
  1401. choices = this.results.find(".select2-result"),
  1402. self = this;
  1403. choices.each2(function (i, choice) {
  1404. var id = self.id(choice.data("select2-data"));
  1405. if (indexOf(id, val) >= 0) {
  1406. choice.addClass("select2-disabled");
  1407. } else {
  1408. choice.removeClass("select2-disabled");
  1409. }
  1410. });
  1411. choices.each2(function (i, choice) {
  1412. if (!choice.hasClass("select2-disabled")) {
  1413. self.highlight(i);
  1414. return false;
  1415. }
  1416. });
  1417. },
  1418. // multi
  1419. resizeSearch: function () {
  1420. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  1421. sideBorderPadding = getSideBorderPadding(this.search);
  1422. minimumWidth = measureTextWidth(this.search) + 10;
  1423. left = this.search.offset().left;
  1424. maxWidth = this.selection.width();
  1425. containerLeft = this.selection.offset().left;
  1426. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  1427. if (searchWidth < minimumWidth) {
  1428. searchWidth = maxWidth - sideBorderPadding;
  1429. }
  1430. if (searchWidth < 40) {
  1431. searchWidth = maxWidth - sideBorderPadding;
  1432. }
  1433. this.search.width(searchWidth);
  1434. },
  1435. // multi
  1436. getVal: function () {
  1437. var val;
  1438. if (this.select) {
  1439. val = this.select.val();
  1440. return val === null ? [] : val;
  1441. } else {
  1442. val = this.opts.element.val();
  1443. return splitVal(val, ",");
  1444. }
  1445. },
  1446. // multi
  1447. setVal: function (val) {
  1448. var unique;
  1449. if (this.select) {
  1450. this.select.val(val);
  1451. } else {
  1452. unique = [];
  1453. // filter out duplicates
  1454. $(val).each(function () {
  1455. if (indexOf(this, unique) < 0) unique.push(this);
  1456. });
  1457. this.opts.element.val(unique.length === 0 ? "" : unique.join(","));
  1458. }
  1459. },
  1460. // multi
  1461. val: function () {
  1462. var val, data = [], self=this;
  1463. if (arguments.length === 0) {
  1464. return this.getVal();
  1465. }
  1466. val = arguments[0];
  1467. if (this.select) {
  1468. // val is a list of ids
  1469. this.setVal(val);
  1470. this.select.find(":selected").each(function () {
  1471. data.push({id: $(this).attr("value"), text: $(this).text()});
  1472. });
  1473. this.updateSelection(data);
  1474. } else {
  1475. val = (val === null) ? [] : val;
  1476. // val is a list of objects
  1477. $(val).each(function () { data.push(self.id(this)); });
  1478. this.setVal(data);
  1479. this.updateSelection(val);
  1480. }
  1481. this.clearSearch();
  1482. },
  1483. // multi
  1484. onSortStart: function() {
  1485. if (this.select) {
  1486. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  1487. }
  1488. // collapse search field into 0 width so its container can be collapsed as well
  1489. this.search.width(0);
  1490. // hide the container
  1491. this.searchContainer.hide();
  1492. },
  1493. // multi
  1494. onSortEnd:function() {
  1495. var val=[], self=this;
  1496. // show search and move it to the end of the list
  1497. this.searchContainer.show();
  1498. // make sure the search container is the last item in the list
  1499. this.searchContainer.appendTo(this.searchContainer.parent());
  1500. // since we collapsed the width in dragStarted, we resize it here
  1501. this.resizeSearch();
  1502. // update selection
  1503. this.selection.find(".select2-search-choice").each(function() {
  1504. val.push(self.opts.id($(this).data("select2-data")));
  1505. });
  1506. this.setVal(val);
  1507. this.triggerChange();
  1508. },
  1509. // multi
  1510. data: function(values) {
  1511. var self=this, ids;
  1512. if (arguments.length === 0) {
  1513. return this.selection
  1514. .find(".select2-search-choice")
  1515. .map(function() { return $(this).data("select2-data"); })
  1516. .get();
  1517. } else {
  1518. ids = $.map(values, function(e) { return self.opts.id(e)});
  1519. this.setVal(ids);
  1520. this.updateSelection(values);
  1521. }
  1522. }
  1523. });
  1524. $.fn.select2 = function () {
  1525. var args = Array.prototype.slice.call(arguments, 0),
  1526. opts,
  1527. select2,
  1528. value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
  1529. this.each(function () {
  1530. if (args.length === 0 || typeof(args[0]) === "object") {
  1531. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1532. opts.element = $(this);
  1533. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1534. multiple = opts.element.attr("multiple");
  1535. } else {
  1536. multiple = opts.multiple || false;
  1537. if ("tags" in opts) {opts.multiple = multiple = true;}
  1538. }
  1539. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1540. select2.init(opts);
  1541. } else if (typeof(args[0]) === "string") {
  1542. if (indexOf(args[0], allowedMethods) < 0) {
  1543. throw "Unknown method: " + args[0];
  1544. }
  1545. value = undefined;
  1546. select2 = $(this).data("select2");
  1547. if (select2 === undefined) return;
  1548. if (args[0] === "container") {
  1549. value=select2.container;
  1550. } else {
  1551. value = select2[args[0]].apply(select2, args.slice(1));
  1552. }
  1553. if (value !== undefined) {return false;}
  1554. } else {
  1555. throw "Invalid arguments to select2 plugin: " + args;
  1556. }
  1557. });
  1558. return (value === undefined) ? this : value;
  1559. };
  1560. // exports
  1561. window.Select2 = {
  1562. query: {
  1563. ajax: ajax,
  1564. local: local,
  1565. tags: tags
  1566. }, util: {
  1567. debounce: debounce,
  1568. markMatch: markMatch
  1569. }, "class": {
  1570. "abstract": AbstractSelect2,
  1571. "single": SingleSelect2,
  1572. "multi": MultiSelect2
  1573. }
  1574. };
  1575. }(jQuery));