select2.js 52 KB

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