select2.js 52 KB

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