select2.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  1. /*
  2. Copyright 2012 Igor Vaynberg
  3. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in
  4. compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software distributed under the License is
  7. distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. See the License for the specific language governing permissions and limitations under the License.
  9. */
  10. (function ($, undefined) {
  11. "use strict";
  12. /*global document, window, jQuery, console */
  13. if (window.Select2 !== undefined) {
  14. return;
  15. }
  16. var KEY, AbstractSelect2, SingleSelect2, MultiSelect2;
  17. KEY = {
  18. TAB: 9,
  19. ENTER: 13,
  20. ESC: 27,
  21. SPACE: 32,
  22. LEFT: 37,
  23. UP: 38,
  24. RIGHT: 39,
  25. DOWN: 40,
  26. SHIFT: 16,
  27. CTRL: 17,
  28. ALT: 18,
  29. PAGE_UP: 33,
  30. PAGE_DOWN: 34,
  31. HOME: 36,
  32. END: 35,
  33. BACKSPACE: 8,
  34. DELETE: 46,
  35. isArrow: function (k) {
  36. k = k.which ? k.which : k;
  37. switch (k) {
  38. case KEY.LEFT:
  39. case KEY.RIGHT:
  40. case KEY.UP:
  41. case KEY.DOWN:
  42. return true;
  43. }
  44. return false;
  45. },
  46. isControl: function (k) {
  47. k = k.which ? k.which : k;
  48. switch (k) {
  49. case KEY.SHIFT:
  50. case KEY.CTRL:
  51. case KEY.ALT:
  52. return true;
  53. }
  54. return false;
  55. },
  56. isFunctionKey: function (k) {
  57. k = k.which ? k.which : k;
  58. return k >= 112 && k <= 123;
  59. }
  60. };
  61. function indexOf(value, array) {
  62. var i = 0, l = array.length, v;
  63. if (value.constructor === String) {
  64. for (; i < l; i = i + 1) if (value.localeCompare(array[i]) === 0) return i;
  65. } else {
  66. for (; i < l; i = i + 1) {
  67. v = array[i];
  68. if (v.constructor === String) {
  69. if (v.localeCompare(value) === 0) return i;
  70. } else {
  71. if (v === value) return i;
  72. }
  73. }
  74. }
  75. return -1;
  76. }
  77. /**
  78. * Compares equality of a and b taking into account that a and b may be strings, in which case localCompare is used
  79. * @param a
  80. * @param b
  81. */
  82. function equal(a, b) {
  83. if (a === b) return true;
  84. if (a === undefined || b === undefined) return false;
  85. if (a === null || b === null) return false;
  86. if (a.constructor === String) return a.localeCompare(b) === 0;
  87. if (b.constructor === String) return b.localeCompare(a) === 0;
  88. return false;
  89. }
  90. /**
  91. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  92. * strings
  93. * @param string
  94. * @param separator
  95. */
  96. function splitVal(string, separator) {
  97. var val, i, l;
  98. if (string === null || string.length < 1) return [];
  99. val = string.split(separator);
  100. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  101. return val;
  102. }
  103. function getSideBorderPadding(element) {
  104. return element.outerWidth() - element.width();
  105. }
  106. function installKeyUpChangeEvent(element) {
  107. element.bind("keydown", function () {
  108. element.data("keyup-change-value", element.val());
  109. });
  110. element.bind("keyup", function () {
  111. if (element.val() !== element.data("keyup-change-value")) {
  112. element.trigger("keyup-change");
  113. }
  114. });
  115. }
  116. /**
  117. * filters mouse events so an event is fired only if the mouse moved.
  118. *
  119. * filters out mouse events that occur when mouse is stationary but
  120. * the elements under the pointer are scrolled.
  121. */
  122. $(document).delegate("*", "mousemove", function (e) {
  123. $(document).data("select2-lastpos", {x: e.pageX, y: e.pageY});
  124. });
  125. function installFilteredMouseMove(element) {
  126. element.bind("mousemove", function (e) {
  127. var lastpos = $(document).data("select2-lastpos");
  128. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  129. $(e.target).trigger("mousemove-filtered", e);
  130. }
  131. });
  132. }
  133. /**
  134. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  135. * within the last quietMillis milliseconds.
  136. *
  137. * @param quietMillis number of milliseconds to wait before invoking fn
  138. * @param fn function to be debounced
  139. * @return debounced version of fn
  140. */
  141. function debounce(quietMillis, fn) {
  142. var timeout;
  143. return function () {
  144. window.clearTimeout(timeout);
  145. timeout = window.setTimeout(fn, quietMillis);
  146. };
  147. }
  148. function installDebouncedScroll(threshold, element) {
  149. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  150. element.bind("scroll", function (e) {
  151. if (indexOf(e.target, element.get()) >= 0) notify(e);
  152. });
  153. }
  154. function killEvent(event) {
  155. event.preventDefault();
  156. event.stopPropagation();
  157. }
  158. function measureTextWidth(e) {
  159. var sizer, width;
  160. sizer = $("<div></div>").css({
  161. position: "absolute",
  162. left: "-1000px",
  163. top: "-1000px",
  164. display: "none",
  165. fontSize: e.css("fontSize"),
  166. fontFamily: e.css("fontFamily"),
  167. fontStyle: e.css("fontStyle"),
  168. fontWeight: e.css("fontWeight"),
  169. letterSpacing: e.css("letterSpacing"),
  170. textTransform: e.css("textTransform"),
  171. whiteSpace: "nowrap"
  172. });
  173. sizer.text(e.val());
  174. $("body").append(sizer);
  175. width = sizer.width();
  176. sizer.remove();
  177. return width;
  178. }
  179. /**
  180. * Produces an ajax-based query function
  181. *
  182. * @param options object containing configuration paramters
  183. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  184. * @param options.url url for the data
  185. * @param options.data a function(searchTerm, pageNumber) that should return an object containing query string parameters for the above url.
  186. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
  187. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  188. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  189. * The expected format is an object containing the following keys:
  190. * results array of objects that will be used as choices
  191. * more (optional) boolean indicating whether there are more results available
  192. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  193. */
  194. function ajax(options) {
  195. var timeout, // current scheduled but not yet executed request
  196. requestSequence = 0, // sequence used to drop out-of-order responses
  197. handler = null,
  198. quietMillis = options.quietMillis || 100;
  199. return function (query) {
  200. window.clearTimeout(timeout);
  201. timeout = window.setTimeout(function () {
  202. requestSequence += 1; // increment the sequence
  203. var requestNumber = requestSequence, // this request's sequence number
  204. data = options.data, // ajax data function
  205. transport = options.transport || $.ajax;
  206. data = data.call(this, query.term, query.page);
  207. if( null !== handler){
  208. handler.abort();
  209. }
  210. handler = transport.call(null, {
  211. url: options.url,
  212. dataType: options.dataType,
  213. data: data,
  214. success: function (data) {
  215. if (requestNumber < requestSequence) {
  216. return;
  217. }
  218. // TODO 3.0 - replace query.page with query so users have access to term, page, etc.
  219. query.callback(options.results(data, query.page));
  220. }
  221. });
  222. }, quietMillis);
  223. };
  224. }
  225. /**
  226. * Produces a query function that works with a local array
  227. *
  228. * @param options object containing configuration parameters. The options parameter can either be an array or an
  229. * object.
  230. *
  231. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  232. *
  233. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  234. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  235. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  236. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  237. * the text.
  238. */
  239. function local(options) {
  240. var data = options, // data elements
  241. text = function (item) { return item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  242. if (!$.isArray(data)) {
  243. text = data.text;
  244. // if text is not a function we assume it to be a key name
  245. if (!$.isFunction(text)) text = function (item) { return item[data.text]; };
  246. data = data.results;
  247. }
  248. return function (query) {
  249. var t = query.term.toUpperCase(), filtered = {};
  250. if (t === "") {
  251. query.callback({results: data});
  252. return;
  253. }
  254. filtered.results = $(data)
  255. .filter(function () {return text(this).toUpperCase().indexOf(t) >= 0;})
  256. .get();
  257. query.callback(filtered);
  258. };
  259. }
  260. // TODO javadoc
  261. function tags(data) {
  262. // TODO even for a function we should probably return a wrapper that does the same object/string check as
  263. // the function for arrays. otherwise only functions that return objects are supported.
  264. if ($.isFunction(data)) {
  265. return data;
  266. }
  267. // if not a function we assume it to be an array
  268. return function (query) {
  269. var t = query.term.toUpperCase(), filtered = {results: []};
  270. $(data).each(function () {
  271. var isObject = this.text!==undefined,
  272. text = isObject ? this.text : this;
  273. if (t === "" || text.toUpperCase().indexOf(t) >= 0) {
  274. filtered.results.push(isObject ? this : {id: this, text: this});
  275. }
  276. });
  277. query.callback(filtered);
  278. };
  279. }
  280. /**
  281. * blurs any Select2 container that has focus when an element outside them was clicked or received focus
  282. */
  283. $(document).ready(function () {
  284. $(document).delegate("*", "mousedown focusin", function (e) {
  285. var target = $(e.target).closest("div.select2-container").get(0);
  286. $(document).find("div.select2-container-active").each(function () {
  287. if (this !== target) $(this).data("select2").blur();
  288. });
  289. });
  290. });
  291. /**
  292. * Creates a new class
  293. *
  294. * @param superClass
  295. * @param methods
  296. */
  297. function clazz(SuperClass, methods) {
  298. var constructor = function () {};
  299. constructor.prototype = new SuperClass;
  300. constructor.prototype.constructor = constructor;
  301. constructor.prototype.parent = SuperClass.prototype;
  302. constructor.prototype = $.extend(constructor.prototype, methods);
  303. return constructor;
  304. }
  305. AbstractSelect2 = clazz(Object, {
  306. bind: function (func) {
  307. var self = this;
  308. return function () {
  309. func.apply(self, arguments);
  310. };
  311. },
  312. init: function (opts) {
  313. var results, search, resultsSelector = ".select2-results";
  314. // prepare options
  315. this.opts = this.prepareOpts(opts);
  316. // destroy if called on an existing component
  317. if (opts.element.data("select2") !== undefined) {
  318. this.destroy();
  319. }
  320. this.container = this.createContainer();
  321. if (opts.element.attr("class") !== undefined) {
  322. this.container.addClass(opts.element.attr("class"));
  323. }
  324. // swap container for the element
  325. this.opts.element
  326. .data("select2", this)
  327. .hide()
  328. .after(this.container);
  329. this.container.data("select2", this);
  330. this.dropdown = this.container.find(".select2-drop");
  331. this.results = results = this.container.find(resultsSelector);
  332. this.search = search = this.container.find("input[type=text]");
  333. this.resultsPage = 0;
  334. // initialize the container
  335. this.initContainer();
  336. installFilteredMouseMove(this.results);
  337. this.container.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
  338. installDebouncedScroll(80, this.results);
  339. this.container.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  340. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  341. if ($.fn.mousewheel) {
  342. results.mousewheel(function (e, delta, deltaX, deltaY) {
  343. var top = results.scrollTop(), height;
  344. if (deltaY > 0 && top - deltaY <= 0) {
  345. results.scrollTop(0);
  346. killEvent(e);
  347. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  348. results.scrollTop(results.get(0).scrollHeight - results.height());
  349. killEvent(e);
  350. }
  351. });
  352. }
  353. installKeyUpChangeEvent(search);
  354. search.bind("keyup-change", this.bind(this.updateResults));
  355. search.bind("focus", function() { search.addClass("select2-focused");});
  356. search.bind("blur", function() { search.removeClass("select2-focused");});
  357. this.container.delegate(resultsSelector, "click", this.bind(function (e) {
  358. if ($(e.target).closest(".select2-result:not(.select2-disabled)").length > 0) {
  359. this.highlightUnderEvent(e);
  360. this.selectHighlighted(e);
  361. } else {
  362. killEvent(e);
  363. this.focusSearch();
  364. }
  365. }));
  366. if ($.isFunction(this.opts.initSelection)) {
  367. // initialize selection based on the current value of the source element
  368. this.initSelection();
  369. // if the user has provided a function that can set selection based on the value of the source element
  370. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  371. this.monitorSource();
  372. }
  373. },
  374. destroy: function () {
  375. var select2 = this.opts.element.data("select2");
  376. if (select2 !== undefined) {
  377. select2.container.remove();
  378. select2.opts.element
  379. .removeData("select2")
  380. .unbind(".select2")
  381. .show();
  382. }
  383. },
  384. prepareOpts: function (opts) {
  385. var element, select;
  386. opts = $.extend({}, {
  387. formatResult: function (data) { return data.text; },
  388. formatSelection: function (data) { return data.text; },
  389. formatNoMatches: function () { return "No matches found"; },
  390. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  391. minimumResultsForSearch: 0
  392. }, opts);
  393. element = opts.element;
  394. if (element.get(0).tagName.toLowerCase() === "select") {
  395. this.select = select = opts.element;
  396. }
  397. // TODO add missing validation logic
  398. if (select) {
  399. /*$.each(["multiple", "ajax", "query", "minimumInputLength"], function () {
  400. if (this in opts) {
  401. throw "Option '" + this + "' is not allowed for Select2 when attached to a select element";
  402. }
  403. });*/
  404. this.opts = opts = $.extend({}, {
  405. miniumInputLength: 0
  406. }, opts);
  407. } else {
  408. this.opts = opts = $.extend({}, {
  409. miniumInputLength: 0
  410. }, opts);
  411. }
  412. if (select) {
  413. opts.query = this.bind(function (query) {
  414. var data = {results: [], more: false},
  415. term = query.term.toUpperCase(),
  416. placeholder = this.getPlaceholder();
  417. element.find("option").each(function (i) {
  418. var e = $(this),
  419. text = e.text();
  420. if (i === 0 && placeholder !== undefined && text === "") return true;
  421. if (text.toUpperCase().indexOf(term) >= 0) {
  422. data.results.push({id: e.attr("value"), text: text});
  423. }
  424. });
  425. query.callback(data);
  426. });
  427. } else {
  428. if (!("query" in opts)) {
  429. if ("ajax" in opts) {
  430. opts.query = ajax(opts.ajax);
  431. } else if ("data" in opts) {
  432. opts.query = local(opts.data);
  433. } else if ("tags" in opts) {
  434. opts.query = tags(opts.tags);
  435. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  436. opts.initSelection = function (element) {
  437. var data = [];
  438. $(splitVal(element.val(), ",")).each(function () {
  439. data.push({id: this, text: this});
  440. });
  441. return data;
  442. };
  443. }
  444. }
  445. }
  446. if (typeof(opts.query) !== "function") {
  447. throw "query function not defined for Select2 " + opts.element.attr("id");
  448. }
  449. return opts;
  450. },
  451. /**
  452. * Monitor the original element for changes and update select2 accordingly
  453. */
  454. monitorSource: function () {
  455. this.opts.element.bind("change.select2", this.bind(function (e) {
  456. if (this.opts.element.data("select2-change-triggered") !== true) {
  457. this.initSelection();
  458. }
  459. }));
  460. },
  461. /**
  462. * Triggers the change event on the source element
  463. */
  464. triggerChange: function () {
  465. // Prevents recursive triggering
  466. this.opts.element.data("select2-change-triggered", true);
  467. this.opts.element.trigger("change");
  468. this.opts.element.data("select2-change-triggered", false);
  469. },
  470. opened: function () {
  471. return this.container.hasClass("select2-dropdown-open");
  472. },
  473. open: function () {
  474. if (this.opened()) return;
  475. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  476. this.updateResults(true);
  477. this.dropdown.show();
  478. this.focusSearch();
  479. },
  480. close: function () {
  481. if (!this.opened()) return;
  482. this.dropdown.hide();
  483. this.container.removeClass("select2-dropdown-open");
  484. this.results.empty();
  485. this.clearSearch();
  486. },
  487. clearSearch: function () {
  488. },
  489. ensureHighlightVisible: function () {
  490. var results = this.results, children, index, child, hb, rb, y, more;
  491. children = results.children(".select2-result");
  492. index = this.highlight();
  493. if (index < 0) return;
  494. child = $(children[index]);
  495. hb = child.offset().top + child.outerHeight();
  496. // if this is the last child lets also make sure select2-more-results is visible
  497. if (index === children.length - 1) {
  498. more = results.find("li.select2-more-results");
  499. if (more.length > 0) {
  500. hb = more.offset().top + more.outerHeight();
  501. }
  502. }
  503. rb = results.offset().top + results.outerHeight();
  504. if (hb > rb) {
  505. results.scrollTop(results.scrollTop() + (hb - rb));
  506. }
  507. y = child.offset().top - results.offset().top;
  508. // make sure the top of the element is visible
  509. if (y < 0) {
  510. results.scrollTop(results.scrollTop() + y); // y is negative
  511. }
  512. },
  513. moveHighlight: function (delta) {
  514. var choices = this.results.children(".select2-result"),
  515. index = this.highlight();
  516. while (index > -1 && index < choices.length) {
  517. index += delta;
  518. if (!$(choices[index]).hasClass("select2-disabled")) {
  519. this.highlight(index);
  520. break;
  521. }
  522. }
  523. },
  524. highlight: function (index) {
  525. var choices = this.results.children(".select2-result");
  526. if (arguments.length === 0) {
  527. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  528. }
  529. choices.removeClass("select2-highlighted");
  530. if (index >= choices.length) index = choices.length - 1;
  531. if (index < 0) index = 0;
  532. $(choices[index]).addClass("select2-highlighted");
  533. this.ensureHighlightVisible();
  534. if (this.opened()) this.focusSearch();
  535. },
  536. highlightUnderEvent: function (event) {
  537. var el = $(event.target).closest(".select2-result");
  538. if (el.length > 0) {
  539. this.highlight(el.index());
  540. }
  541. },
  542. loadMoreIfNeeded: function () {
  543. var results = this.results,
  544. more = results.find("li.select2-more-results"),
  545. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  546. offset = -1, // index of first element without data
  547. page = this.resultsPage + 1;
  548. if (more.length === 0) return;
  549. below = more.offset().top - results.offset().top - results.height();
  550. if (below <= 0) {
  551. more.addClass("select2-active");
  552. this.opts.query({term: this.search.val(), page: page, callback: this.bind(function (data) {
  553. var parts = [], self = this;
  554. $(data.results).each(function () {
  555. parts.push("<li class='select2-result'>");
  556. parts.push(self.opts.formatResult(this));
  557. parts.push("</li>");
  558. });
  559. more.before(parts.join(""));
  560. results.find(".select2-result").each(function (i) {
  561. var e = $(this);
  562. if (e.data("select2-data") !== undefined) {
  563. offset = i;
  564. } else {
  565. e.data("select2-data", data.results[i - offset - 1]);
  566. }
  567. });
  568. if (data.more) {
  569. more.removeClass("select2-active");
  570. } else {
  571. more.remove();
  572. }
  573. this.resultsPage = page;
  574. })});
  575. }
  576. },
  577. /**
  578. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  579. */
  580. updateResults: function (initial) {
  581. var search = this.search, results = this.results, opts = this.opts;
  582. search.addClass("select2-active");
  583. function render(html) {
  584. results.html(html);
  585. results.scrollTop(0);
  586. search.removeClass("select2-active");
  587. }
  588. if (search.val().length < opts.minimumInputLength) {
  589. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  590. return;
  591. }
  592. this.resultsPage = 1;
  593. opts.query({term: search.val(), page: this.resultsPage, callback: this.bind(function (data) {
  594. var parts = [], // html parts
  595. def; // default choice
  596. // create a default choice and prepend it to the list
  597. if (this.opts.createSearchChoice && search.val() !== "") {
  598. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  599. if (def !== undefined && def !== null && def.id !== undefined && def.id !== null) {
  600. if ($(data.results).filter(
  601. function () {
  602. return equal(this.id, def.id);
  603. }).length === 0) {
  604. data.results.unshift(def);
  605. }
  606. }
  607. }
  608. if (data.results.length === 0) {
  609. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  610. return;
  611. }
  612. $(data.results).each(function () {
  613. parts.push("<li class='select2-result'>");
  614. parts.push(opts.formatResult(this));
  615. parts.push("</li>");
  616. });
  617. if (data.more === true) {
  618. parts.push("<li class='select2-more-results'>Loading more results...</li>");
  619. }
  620. render(parts.join(""));
  621. results.children(".select2-result").each(function (i) {
  622. var d = data.results[i];
  623. $(this).data("select2-data", d);
  624. });
  625. this.postprocessResults(data, initial);
  626. })});
  627. },
  628. cancel: function () {
  629. this.close();
  630. },
  631. blur: function () {
  632. /* we do this in a timeout so that current event processing can complete before this code is executed.
  633. this allows tab index to be preserved even if this code blurs the textfield */
  634. window.setTimeout(this.bind(function () {
  635. this.close();
  636. this.container.removeClass("select2-container-active");
  637. this.clearSearch();
  638. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  639. this.search.blur();
  640. }), 10);
  641. },
  642. focusSearch: function () {
  643. /* we do this in a timeout so that current event processing can complete before this code is executed.
  644. this makes sure the search field is focussed even if the current event would blur it */
  645. window.setTimeout(this.bind(function () {
  646. this.search.focus();
  647. }), 10);
  648. },
  649. selectHighlighted: function () {
  650. var data = this.results.find(".select2-highlighted:not(.select2-disabled)").data("select2-data");
  651. if (data) {
  652. this.onSelect(data);
  653. }
  654. },
  655. getPlaceholder: function () {
  656. return this.opts.element.attr("placeholder") || this.opts.element.data("placeholder") || this.opts.placeholder;
  657. },
  658. /**
  659. * Get the desired width for the container element. This is
  660. * derived first from option `width` passed to select2, then
  661. * the inline 'style' on the original element, and finally
  662. * falls back to the jQuery calculated element width.
  663. *
  664. * @returns The width string (with units) for the container.
  665. */
  666. getContainerWidth: function () {
  667. var style, attrs, matches, i, l;
  668. if (this.opts.width !== undefined)
  669. return this.opts.width;
  670. style = this.opts.element.attr('style');
  671. if (style !== undefined) {
  672. attrs = style.split(';');
  673. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  674. matches = attrs[i].replace(/\s/g, '')
  675. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  676. if (matches !== null && matches.length >= 1)
  677. return matches[1];
  678. }
  679. }
  680. return this.opts.element.width() + 'px';
  681. }
  682. });
  683. SingleSelect2 = clazz(AbstractSelect2, {
  684. createContainer: function () {
  685. return $("<div></div>", {
  686. "class": "select2-container",
  687. "style": "width: " + this.getContainerWidth()
  688. }).html([
  689. " <a href='javascript:void(0)' class='select2-choice'>",
  690. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  691. " <div><b></b></div>" ,
  692. "</a>",
  693. " <div class='select2-drop' style='display:none;'>" ,
  694. " <div class='select2-search'>" ,
  695. " <input type='text' autocomplete='off'/>" ,
  696. " </div>" ,
  697. " <ul class='select2-results'>" ,
  698. " </ul>" ,
  699. "</div>"].join(""));
  700. },
  701. open: function () {
  702. if (this.opened()) return;
  703. this.parent.open.apply(this, arguments);
  704. },
  705. close: function () {
  706. if (!this.opened()) return;
  707. this.parent.close.apply(this, arguments);
  708. },
  709. focus: function () {
  710. this.close();
  711. this.selection.focus();
  712. },
  713. isFocused: function () {
  714. return this.selection.is(":focus");
  715. },
  716. cancel: function () {
  717. this.parent.cancel.apply(this, arguments);
  718. this.selection.focus();
  719. },
  720. initContainer: function () {
  721. var selection, container = this.container, clickingInside = false,
  722. selector = ".select2-choice";
  723. this.selection = selection = container.find(selector);
  724. this.search.bind("keydown", this.bind(function (e) {
  725. switch (e.which) {
  726. case KEY.UP:
  727. case KEY.DOWN:
  728. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  729. killEvent(e);
  730. return;
  731. case KEY.TAB:
  732. case KEY.ENTER:
  733. this.selectHighlighted();
  734. killEvent(e);
  735. return;
  736. case KEY.ESC:
  737. this.cancel(e);
  738. e.preventDefault();
  739. return;
  740. }
  741. }));
  742. container.delegate(selector, "click", this.bind(function (e) {
  743. clickingInside = true;
  744. if (this.opened()) {
  745. this.close();
  746. selection.focus();
  747. } else {
  748. this.open();
  749. }
  750. e.preventDefault();
  751. clickingInside = false;
  752. }));
  753. container.delegate(selector, "keydown", this.bind(function (e) {
  754. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  755. return;
  756. }
  757. this.open();
  758. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN || e.which === KEY.SPACE) {
  759. // prevent the page from scrolling
  760. killEvent(e);
  761. }
  762. if (e.which === KEY.ENTER) {
  763. // do not propagate the event otherwise we open, and propagate enter which closes
  764. killEvent(e);
  765. }
  766. }));
  767. container.delegate(selector, "focus", function () { container.addClass("select2-container-active"); });
  768. container.delegate(selector, "blur", this.bind(function () {
  769. if (clickingInside) return;
  770. if (!this.opened()) this.blur();
  771. }));
  772. selection.delegate("abbr", "click", this.bind(function (e) {
  773. this.val("");
  774. killEvent(e);
  775. this.close();
  776. this.triggerChange();
  777. }));
  778. this.setPlaceholder();
  779. },
  780. /**
  781. * Sets selection based on source element's value
  782. */
  783. initSelection: function () {
  784. var selected;
  785. if (this.opts.element.val() === "") {
  786. this.updateSelection({id: "", text: ""});
  787. } else {
  788. selected = this.opts.initSelection.call(null, this.opts.element);
  789. if (selected !== undefined && selected !== null) {
  790. this.updateSelection(selected);
  791. }
  792. }
  793. this.close();
  794. this.setPlaceholder();
  795. },
  796. prepareOpts: function () {
  797. var opts = this.parent.prepareOpts.apply(this, arguments);
  798. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  799. // install sthe selection initializer
  800. opts.initSelection = function (element) {
  801. var selected = element.find(":selected");
  802. // a single select box always has a value, no need to null check 'selected'
  803. return {id: selected.attr("value"), text: selected.text()};
  804. };
  805. }
  806. return opts;
  807. },
  808. setPlaceholder: function () {
  809. var placeholder = this.getPlaceholder();
  810. if (this.opts.element.val() === "" && placeholder !== undefined) {
  811. // check for a first blank option if attached to a select
  812. if (this.select && this.select.find("option:first").text() !== "") return;
  813. if (typeof(placeholder) === "object") {
  814. this.updateSelection(placeholder);
  815. } else {
  816. this.selection.find("span").html(placeholder);
  817. }
  818. this.selection.addClass("select2-default");
  819. this.selection.find("abbr").hide();
  820. }
  821. },
  822. postprocessResults: function (data, initial) {
  823. var selected = 0, self = this, showSearchInput = true;
  824. // find the selected element in the result list
  825. this.results.find(".select2-result").each(function (i) {
  826. if (equal($(this).data("select2-data").id, self.opts.element.val())) {
  827. selected = i;
  828. return false;
  829. }
  830. });
  831. // and highlight it
  832. this.highlight(selected);
  833. // hide the search box if this is the first we got the results and there are a few of them
  834. if (initial === true) {
  835. showSearchInput = data.results.length >= this.opts.minimumResultsForSearch;
  836. this.search.parent().toggle(showSearchInput);
  837. //add "select2-with-searchbox" to the container if search box is shown
  838. this.container[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  839. }
  840. },
  841. onSelect: function (data) {
  842. var old = this.opts.element.val();
  843. this.opts.element.val(data.id);
  844. this.updateSelection(data);
  845. this.close();
  846. this.selection.focus();
  847. if (!equal(old, data.id)) { this.triggerChange(); }
  848. },
  849. updateSelection: function (data) {
  850. this.selection
  851. .find("span")
  852. .html(this.opts.formatSelection(data));
  853. this.selection.removeClass("select2-default");
  854. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  855. this.selection.find("abbr").show();
  856. }
  857. },
  858. val: function () {
  859. var val, data = null;
  860. if (arguments.length === 0) {
  861. return this.opts.element.val();
  862. }
  863. val = arguments[0];
  864. if (this.select) {
  865. // val is an id
  866. this.select
  867. .val(val)
  868. .find(":selected").each(function () {
  869. data = {id: $(this).attr("value"), text: $(this).text()};
  870. return false;
  871. });
  872. this.updateSelection(data);
  873. } else {
  874. // val is an object. !val is true for [undefined,null,'']
  875. this.opts.element.val(!val ? "" : val.id);
  876. this.updateSelection(val);
  877. }
  878. this.setPlaceholder();
  879. },
  880. clearSearch: function () {
  881. this.search.val("");
  882. }
  883. });
  884. MultiSelect2 = clazz(AbstractSelect2, {
  885. createContainer: function () {
  886. return $("<div></div>", {
  887. "class": "select2-container select2-container-multi",
  888. "style": "width: " + this.getContainerWidth()
  889. }).html([
  890. " <ul class='select2-choices'>",
  891. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  892. " <li class='select2-search-field'>" ,
  893. " <input type='text' autocomplete='off' style='width: 25px;'>" ,
  894. " </li>" ,
  895. "</ul>" ,
  896. "<div class='select2-drop' style='display:none;'>" ,
  897. " <ul class='select2-results'>" ,
  898. " </ul>" ,
  899. "</div>"].join(""));
  900. },
  901. prepareOpts: function () {
  902. var opts = this.parent.prepareOpts.apply(this, arguments);
  903. opts = $.extend({}, {
  904. closeOnSelect: true
  905. }, opts);
  906. // TODO validate placeholder is a string if specified
  907. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  908. // install sthe selection initializer
  909. opts.initSelection = function (element) {
  910. var data = [];
  911. element.find(":selected").each(function () {
  912. data.push({id: $(this).attr("value"), text: $(this).text()});
  913. });
  914. return data;
  915. };
  916. }
  917. return opts;
  918. },
  919. initContainer: function () {
  920. var selector = ".select2-choices", selection;
  921. this.searchContainer = this.container.find(".select2-search-field");
  922. this.selection = selection = this.container.find(selector);
  923. this.search.bind("keydown", this.bind(function (e) {
  924. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  925. this.close();
  926. var choices,
  927. selected = selection.find(".select2-search-choice-focus");
  928. if (selected.length > 0) {
  929. this.unselect(selected.first());
  930. this.search.width(10);
  931. killEvent(e);
  932. return;
  933. }
  934. choices = selection.find(".select2-search-choice");
  935. if (choices.length > 0) {
  936. choices.last().addClass("select2-search-choice-focus");
  937. }
  938. } else {
  939. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  940. }
  941. if (this.opened()) {
  942. switch (e.which) {
  943. case KEY.UP:
  944. case KEY.DOWN:
  945. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  946. killEvent(e);
  947. return;
  948. case KEY.ENTER:
  949. this.selectHighlighted();
  950. killEvent(e);
  951. return;
  952. case KEY.ESC:
  953. this.cancel(e);
  954. e.preventDefault();
  955. return;
  956. }
  957. }
  958. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  959. return;
  960. }
  961. this.open();
  962. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  963. // prevent the page from scrolling
  964. killEvent(e);
  965. }
  966. }));
  967. this.search.bind("keyup", this.bind(this.resizeSearch));
  968. this.container.delegate(selector, "click", this.bind(function (e) {
  969. this.open();
  970. this.focusSearch();
  971. e.preventDefault();
  972. }));
  973. this.container.delegate(selector, "focus", this.bind(function () {
  974. this.container.addClass("select2-container-active");
  975. this.clearPlaceholder();
  976. }));
  977. // set the placeholder if necessary
  978. this.clearSearch();
  979. },
  980. initSelection: function () {
  981. var data;
  982. if (this.opts.element.val() === "") {
  983. this.updateSelection([]);
  984. }
  985. if (this.select || this.opts.element.val() !== "") {
  986. data = this.opts.initSelection.call(null, this.opts.element);
  987. if (data !== undefined && data !== null) {
  988. this.updateSelection(data);
  989. }
  990. }
  991. this.close();
  992. // set the placeholder if necessary
  993. this.clearSearch();
  994. },
  995. clearSearch: function () {
  996. var placeholder = this.getPlaceholder();
  997. if (placeholder !== undefined
  998. && this.getVal().length === 0
  999. && this.search.hasClass("select2-focused")===false) {
  1000. this.search.val(placeholder).addClass("select2-default");
  1001. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1002. this.search.width(this.getContainerWidth());
  1003. } else {
  1004. this.search.val("").width(10);
  1005. }
  1006. },
  1007. clearPlaceholder: function () {
  1008. if (this.search.hasClass("select2-default")) {
  1009. this.search.val("").removeClass("select2-default");
  1010. }
  1011. },
  1012. open: function () {
  1013. if (this.opened()) return;
  1014. this.parent.open.apply(this, arguments);
  1015. this.resizeSearch();
  1016. this.focusSearch();
  1017. },
  1018. close: function () {
  1019. if (!this.opened()) return;
  1020. this.parent.close.apply(this, arguments);
  1021. },
  1022. focus: function () {
  1023. this.close();
  1024. this.search.focus();
  1025. },
  1026. isFocused: function () {
  1027. return this.search.hasClass("select2-focused");
  1028. },
  1029. updateSelection: function (data) {
  1030. var ids = [], filtered = [], self = this;
  1031. // filter out duplicates
  1032. $(data).each(function () {
  1033. if (indexOf(this.id, ids) < 0) {
  1034. ids.push(this.id);
  1035. filtered.push(this);
  1036. }
  1037. });
  1038. data = filtered;
  1039. this.selection.find(".select2-search-choice").remove();
  1040. $(data).each(function () {
  1041. self.addSelectedChoice(this);
  1042. });
  1043. self.postprocessResults();
  1044. },
  1045. onSelect: function (data) {
  1046. this.addSelectedChoice(data);
  1047. if (this.select) { this.postprocessResults(); }
  1048. if (this.opts.closeOnSelect) {
  1049. this.close();
  1050. this.search.width(10);
  1051. } else {
  1052. this.search.width(10);
  1053. this.resizeSearch();
  1054. }
  1055. // since its not possible to select an element that has already been
  1056. // added we do not need to check if this is a new element before firing change
  1057. this.triggerChange();
  1058. this.focusSearch();
  1059. },
  1060. cancel: function () {
  1061. this.close();
  1062. this.focusSearch();
  1063. },
  1064. addSelectedChoice: function (data) {
  1065. var choice,
  1066. id = data.id,
  1067. parts,
  1068. val = this.getVal();
  1069. parts = ["<li class='select2-search-choice'>",
  1070. this.opts.formatSelection(data),
  1071. "<a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>",
  1072. "</li>"
  1073. ];
  1074. choice = $(parts.join(""));
  1075. choice.find("a")
  1076. .bind("click dblclick", this.bind(function (e) {
  1077. this.unselect($(e.target));
  1078. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1079. killEvent(e);
  1080. this.close();
  1081. this.focusSearch();
  1082. })).bind("focus", this.bind(function () {
  1083. this.container.addClass("select2-container-active");
  1084. }));
  1085. choice.data("select2-data", data);
  1086. choice.insertBefore(this.searchContainer);
  1087. val.push(id);
  1088. this.setVal(val);
  1089. },
  1090. unselect: function (selected) {
  1091. var val = this.getVal(),
  1092. index;
  1093. selected = selected.closest(".select2-search-choice");
  1094. if (selected.length === 0) {
  1095. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1096. }
  1097. index = indexOf(selected.data("select2-data").id, val);
  1098. if (index >= 0) {
  1099. val.splice(index, 1);
  1100. this.setVal(val);
  1101. if (this.select) this.postprocessResults();
  1102. }
  1103. selected.remove();
  1104. this.triggerChange();
  1105. },
  1106. postprocessResults: function () {
  1107. var val = this.getVal(),
  1108. choices = this.results.find(".select2-result"),
  1109. self = this;
  1110. choices.each(function () {
  1111. var choice = $(this), id = choice.data("select2-data").id;
  1112. if (indexOf(id, val) >= 0) {
  1113. choice.addClass("select2-disabled");
  1114. } else {
  1115. choice.removeClass("select2-disabled");
  1116. }
  1117. });
  1118. choices.each(function (i) {
  1119. if (!$(this).hasClass("select2-disabled")) {
  1120. self.highlight(i);
  1121. return false;
  1122. }
  1123. });
  1124. },
  1125. resizeSearch: function () {
  1126. var minimumWidth, left, maxWidth, containerLeft, searchWidth;
  1127. minimumWidth = measureTextWidth(this.search) + 10;
  1128. left = this.search.offset().left;
  1129. maxWidth = this.selection.width();
  1130. containerLeft = this.selection.offset().left;
  1131. searchWidth = maxWidth - (left - containerLeft) - getSideBorderPadding(this.search);
  1132. if (searchWidth < minimumWidth) {
  1133. searchWidth = maxWidth - getSideBorderPadding(this.search);
  1134. }
  1135. if (searchWidth < 40) {
  1136. searchWidth = maxWidth - getSideBorderPadding(this.search);
  1137. }
  1138. this.search.width(searchWidth);
  1139. },
  1140. getVal: function () {
  1141. var val;
  1142. if (this.select) {
  1143. val = this.select.val();
  1144. return val === null ? [] : val;
  1145. } else {
  1146. val = this.opts.element.val();
  1147. return splitVal(val, ",");
  1148. }
  1149. },
  1150. setVal: function (val) {
  1151. var unique = [];
  1152. if (this.select) {
  1153. this.select.val(val);
  1154. } else {
  1155. // filter out duplicates
  1156. $(val).each(function () {
  1157. if (indexOf(this, unique) < 0) unique.push(this);
  1158. });
  1159. this.opts.element.val(unique.length === 0 ? "" : unique.join(","));
  1160. }
  1161. },
  1162. val: function () {
  1163. var val, data = [];
  1164. if (arguments.length === 0) {
  1165. return this.getVal();
  1166. }
  1167. val = arguments[0];
  1168. if (this.select) {
  1169. // val is a list of ids
  1170. this.setVal(val);
  1171. this.select.find(":selected").each(function () {
  1172. data.push({id: $(this).attr("value"), text: $(this).text()});
  1173. });
  1174. this.updateSelection(data);
  1175. } else {
  1176. val = (val === null) ? [] : val;
  1177. this.setVal(val);
  1178. // val is a list of objects
  1179. $(val).each(function () { data.push(this.id); });
  1180. this.setVal(data);
  1181. this.updateSelection(val);
  1182. }
  1183. this.clearSearch();
  1184. }
  1185. });
  1186. $.fn.select2 = function () {
  1187. var args = Array.prototype.slice.call(arguments, 0),
  1188. opts,
  1189. select2,
  1190. value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused"];
  1191. this.each(function () {
  1192. if (args.length === 0 || typeof(args[0]) === "object") {
  1193. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1194. opts.element = $(this);
  1195. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1196. multiple = opts.element.attr("multiple");
  1197. } else {
  1198. multiple = opts.multiple || false;
  1199. if ("tags" in opts) {opts.multiple = multiple = true;}
  1200. }
  1201. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1202. select2.init(opts);
  1203. } else if (typeof(args[0]) === "string") {
  1204. if (indexOf(args[0], allowedMethods) < 0) {
  1205. throw "Unknown method: " + args[0];
  1206. }
  1207. value = undefined;
  1208. select2 = $(this).data("select2");
  1209. if (select2 === undefined) return;
  1210. value = select2[args[0]].apply(select2, args.slice(1));
  1211. if (value !== undefined) {return false;}
  1212. } else {
  1213. throw "Invalid arguments to select2 plugin: " + args;
  1214. }
  1215. });
  1216. return (value === undefined) ? this : value;
  1217. };
  1218. // exports
  1219. window.Select2 = {
  1220. query: {
  1221. ajax: ajax,
  1222. local: local,
  1223. tags: tags
  1224. }, util: {
  1225. debounce: debounce
  1226. }, "class": {
  1227. "abstract": AbstractSelect2,
  1228. "single": SingleSelect2,
  1229. "multi": MultiSelect2
  1230. }
  1231. };
  1232. }(jQuery));