select2.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. (function ($) {
  18. "use strict";
  19. /*global document, window, jQuery, console */
  20. var KEY = {
  21. TAB: 9,
  22. ENTER: 13,
  23. ESC: 27,
  24. SPACE: 32,
  25. LEFT: 37,
  26. UP: 38,
  27. RIGHT: 39,
  28. DOWN: 40,
  29. SHIFT: 16,
  30. CTRL: 17,
  31. ALT: 18,
  32. PAGE_UP: 33,
  33. PAGE_DOWN: 34,
  34. HOME: 36,
  35. END: 35,
  36. BACKSPACE: 8,
  37. DELETE: 46,
  38. isArrow: function (k) {
  39. k = k.which ? k.which : k;
  40. switch (k) {
  41. case KEY.LEFT:
  42. case KEY.RIGHT:
  43. case KEY.UP:
  44. case KEY.DOWN:
  45. return true;
  46. }
  47. return false;
  48. },
  49. isControl: function (k) {
  50. k = k.which ? k.which : k;
  51. switch (k) {
  52. case KEY.SHIFT:
  53. case KEY.CTRL:
  54. case KEY.ALT:
  55. return true;
  56. }
  57. return false;
  58. },
  59. isFunctionKey: function (k) {
  60. k = k.which ? k.which : k;
  61. return k >= 112 && k <= 123;
  62. }
  63. };
  64. function indexOf(value, array) {
  65. var i = 0, l = array.length, v;
  66. if (value.constructor === String) {
  67. for (; i < l; i++) if (value.localeCompare(array[i]) === 0) return i;
  68. } else {
  69. for (; i < l; i++) {
  70. v = array[i];
  71. if (v.constructor === String) {
  72. if (v.localeCompare(value) === 0) return i;
  73. } else {
  74. if (v === value) return i;
  75. }
  76. }
  77. }
  78. return -1;
  79. }
  80. function getSideBorderPadding(element) {
  81. return element.outerWidth() - element.width();
  82. }
  83. function installKeyUpChangeEvent(element) {
  84. element.bind("keydown", function () {
  85. element.data("keyup-change-value", element.val());
  86. });
  87. element.bind("keyup", function () {
  88. if (element.val() !== element.data("keyup-change-value")) {
  89. element.trigger("keyup-change");
  90. }
  91. });
  92. }
  93. /**
  94. * filters mouse events so an event is fired only if the mouse moved.
  95. *
  96. * filters out mouse events that occur when mouse is stationary but
  97. * the elements under the pointer are scrolled.
  98. */
  99. $(document).delegate("*", "mousemove", function (e) {
  100. $(this).data("select2-lastpos", {x: e.pageX, y: e.pageY});
  101. });
  102. function installFilteredMouseMove(element) {
  103. var doc = $(document);
  104. element.bind("mousemove", function (e) {
  105. var lastpos = doc.data("select2-lastpos");
  106. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  107. $(e.target).trigger("mousemove-filtered", e);
  108. }
  109. });
  110. }
  111. function debounce(threshold, fn) {
  112. var timeout;
  113. return function () {
  114. window.clearTimeout(timeout);
  115. timeout = window.setTimeout(fn, threshold);
  116. };
  117. }
  118. function installDebouncedScroll(threshold, element) {
  119. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  120. element.bind("scroll", function (e) {
  121. if (indexOf(e.target, element.get()) >= 0) notify(e);
  122. });
  123. }
  124. function killEvent(event) {
  125. event.preventDefault();
  126. event.stopPropagation();
  127. }
  128. function measureTextWidth(e) {
  129. var sizer, width;
  130. sizer = $("<div></div>").css({
  131. position: "absolute",
  132. left: "-1000px",
  133. top: "-1000px",
  134. display: "none",
  135. fontSize: e.css("fontSize"),
  136. fontFamily: e.css("fontFamily"),
  137. fontStyle: e.css("fontStyle"),
  138. fontWeight: e.css("fontWeight"),
  139. letterSpacing: e.css("letterSpacing"),
  140. textTransform: e.css("textTransform"),
  141. whiteSpace: "nowrap"
  142. });
  143. sizer.text(e.val());
  144. $("body").append(sizer);
  145. width = sizer.width();
  146. sizer.remove();
  147. return width;
  148. }
  149. /**
  150. * blurs any Select2 container that has focus when an element outside them was clicked or received focus
  151. */
  152. $(document).ready(function () {
  153. $(document).delegate("*", "mousedown focusin", function (e) {
  154. var target = $(e.target).closest("div.select2-container").get(0);
  155. $(document).find("div.select2-container-active").each(function () {
  156. if (this !== target) $(this).data("select2").blur();
  157. });
  158. });
  159. });
  160. /**
  161. *
  162. * @param opts
  163. */
  164. function AbstractSelect2() {
  165. }
  166. AbstractSelect2.prototype.bind = function (func) {
  167. var self = this;
  168. return function () {
  169. func.apply(self, arguments);
  170. };
  171. };
  172. AbstractSelect2.prototype.init = function (opts) {
  173. var results, search, resultsSelector = ".select2-results";
  174. // prepare options
  175. this.opts = this.prepareOpts(opts);
  176. this.container = this.createContainer();
  177. if (opts.element.attr("class") !== undefined) {
  178. this.container.addClass(opts.element.attr("class"));
  179. }
  180. // swap container for the element
  181. this.opts.element.data("select2", this)
  182. .hide()
  183. .after(this.container);
  184. this.container.data("select2", this);
  185. this.dropdown = this.container.find(".select2-drop");
  186. this.results = results = this.container.find(resultsSelector);
  187. this.search = search = this.container.find("input[type=text]");
  188. this.resultsPage = 0;
  189. // initialize the container
  190. this.initContainer();
  191. installFilteredMouseMove(this.results);
  192. this.container.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
  193. installDebouncedScroll(80, this.results);
  194. this.container.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  195. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  196. if ($.fn.mousewheel) {
  197. results.mousewheel(function (e, delta, deltaX, deltaY) {
  198. var top = results.scrollTop(), height;
  199. if (deltaY > 0 && top - deltaY <= 0) {
  200. results.scrollTop(0);
  201. killEvent(e);
  202. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  203. results.scrollTop(results.get(0).scrollHeight - results.height());
  204. killEvent(e);
  205. }
  206. });
  207. }
  208. installKeyUpChangeEvent(search);
  209. search.bind("keyup-change", this.bind(this.updateResults));
  210. this.container.delegate(resultsSelector, "click", this.bind(function (e) {
  211. if ($(e.target).closest(".select2-result:not(.select2-disabled)").length > 0) {
  212. this.highlightUnderEvent(e);
  213. this.selectHighlighted(e);
  214. } else {
  215. killEvent(e);
  216. this.focusSearch();
  217. }
  218. }));
  219. };
  220. AbstractSelect2.prototype.prepareOpts = function (opts) {
  221. var element, select;
  222. opts = $.extend({}, {
  223. formatResult: function (data) { return data.text; },
  224. formatSelection: function (data) { return data.text; },
  225. formatNoMatches: function () { return "No matches found"; },
  226. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  227. minimumResultsForSearch: 0
  228. }, opts);
  229. element = opts.element;
  230. if (element.get(0).tagName.toLowerCase() === "select") {
  231. this.select = select = opts.element;
  232. }
  233. // TODO add missing validation logic
  234. if (select) {
  235. /*$.each(["multiple", "ajax", "query", "minimumInputLength"], function () {
  236. if (this in opts) {
  237. throw "Option '" + this + "' is not allowed for Select2 when attached to a select element";
  238. }
  239. });*/
  240. this.opts = opts = $.extend({}, {
  241. miniumInputLength: 0
  242. }, opts);
  243. } else {
  244. this.opts = opts = $.extend({}, {
  245. miniumInputLength: 0
  246. }, opts);
  247. }
  248. if (select) {
  249. opts.query = this.bind(function (query) {
  250. var data = {results: [], more: false},
  251. term = query.term.toUpperCase(),
  252. placeholder = this.getPlaceholder();
  253. element.find("option").each(function (i) {
  254. var e = $(this),
  255. text = e.text();
  256. if (i === 0 && placeholder !== undefined && text === "") return true;
  257. if (text.toUpperCase().indexOf(term) >= 0) {
  258. data.results.push({id: e.attr("value"), text: text});
  259. }
  260. });
  261. query.callback(data);
  262. });
  263. } else {
  264. if (!("query" in opts)) {
  265. if ("ajax" in opts) {
  266. opts.query = (function () {
  267. var timeout, // current scheduled but not yet executed request
  268. requestSequence = 0, // sequence used to drop out-of-order responses
  269. quietMillis = opts.ajax.quietMillis || 100;
  270. return function (query) {
  271. window.clearTimeout(timeout);
  272. timeout = window.setTimeout(function () {
  273. requestSequence += 1; // increment the sequence
  274. var requestNumber = requestSequence, // this request's sequence number
  275. options = opts.ajax, // ajax parameters
  276. data = options.data; // ajax data function
  277. data = data.call(this, query.term, query.page);
  278. $.ajax({
  279. url: options.url,
  280. dataType: options.dataType,
  281. data: data,
  282. success: function (data) {
  283. if (requestNumber < requestSequence) {
  284. return;
  285. }
  286. query.callback(options.results(data, query.page));
  287. }
  288. });
  289. }, quietMillis);
  290. };
  291. }());
  292. } else if ("data" in opts) {
  293. opts.query = (function () {
  294. var data = opts.data, // data elements
  295. text = function (item) { return item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  296. if (!$.isArray(data)) {
  297. text = data.text;
  298. // if text is not a function we assume it to be a key name
  299. if (!$.isFunction(text)) text = function (item) { return item[data.text]; };
  300. data = data.results;
  301. }
  302. return function (query) {
  303. var t = query.term.toUpperCase(), filtered = {};
  304. if (t === "") {
  305. query.callback({results: data});
  306. return;
  307. }
  308. filtered.result = $(data)
  309. .filter(function () {return text(this).toUpperCase().indexOf(t) >= 0;})
  310. .get();
  311. query.callback(filtered);
  312. };
  313. }());
  314. }
  315. }
  316. }
  317. if (typeof(opts.query) !== "function") {
  318. throw "query function not defined for Select2 " + opts.element.attr("id");
  319. }
  320. return opts;
  321. };
  322. AbstractSelect2.prototype.opened = function () {
  323. return this.container.hasClass("select2-dropdown-open");
  324. };
  325. AbstractSelect2.prototype.alignDropdown = function () {
  326. this.dropdown.css({
  327. top: this.container.height(),
  328. width: this.container.outerWidth() - getSideBorderPadding(this.dropdown)
  329. });
  330. };
  331. AbstractSelect2.prototype.open = function () {
  332. var width;
  333. if (this.opened()) return;
  334. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  335. this.updateResults(true);
  336. this.alignDropdown();
  337. this.dropdown.show();
  338. this.focusSearch();
  339. };
  340. AbstractSelect2.prototype.close = function () {
  341. if (!this.opened()) return;
  342. this.dropdown.hide();
  343. this.container.removeClass("select2-dropdown-open");
  344. this.results.empty();
  345. this.clearSearch();
  346. };
  347. AbstractSelect2.prototype.clearSearch = function () {
  348. };
  349. AbstractSelect2.prototype.ensureHighlightVisible = function () {
  350. var results = this.results, children, index, child, hb, rb, y, more;
  351. children = results.children(".select2-result");
  352. index = this.highlight();
  353. if (index < 0) return;
  354. child = $(children[index]);
  355. hb = child.offset().top + child.outerHeight();
  356. // if this is the last child lets also make sure select2-more-results is visible
  357. if (index === children.length - 1) {
  358. more = results.find("li.select2-more-results");
  359. if (more.length > 0) {
  360. hb = more.offset().top + more.outerHeight();
  361. }
  362. }
  363. rb = results.offset().top + results.outerHeight();
  364. if (hb > rb) {
  365. results.scrollTop(results.scrollTop() + (hb - rb));
  366. }
  367. y = child.offset().top - results.offset().top;
  368. // make sure the top of the element is visible
  369. if (y < 0) {
  370. results.scrollTop(results.scrollTop() + y); // y is negative
  371. }
  372. };
  373. AbstractSelect2.prototype.moveHighlight = function (delta) {
  374. var choices = this.results.children(".select2-result"),
  375. index = this.highlight();
  376. while (index > -1 && index < choices.length) {
  377. index += delta;
  378. if (!$(choices[index]).hasClass("select2-disabled")) {
  379. this.highlight(index);
  380. break;
  381. }
  382. }
  383. };
  384. AbstractSelect2.prototype.highlight = function (index) {
  385. var choices = this.results.children(".select2-result");
  386. if (arguments.length === 0) {
  387. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  388. }
  389. choices.removeClass("select2-highlighted");
  390. if (index >= choices.length) index = choices.length - 1;
  391. if (index < 0) index = 0;
  392. $(choices[index]).addClass("select2-highlighted");
  393. this.ensureHighlightVisible();
  394. if (this.opened()) this.focusSearch();
  395. };
  396. AbstractSelect2.prototype.highlightUnderEvent = function (event) {
  397. var el = $(event.target).closest(".select2-result");
  398. if (el.length > 0) {
  399. this.highlight(el.index());
  400. }
  401. };
  402. AbstractSelect2.prototype.loadMoreIfNeeded = function () {
  403. var results = this.results,
  404. more = results.find("li.select2-more-results"),
  405. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  406. offset = -1, // index of first element without data
  407. page = this.resultsPage + 1;
  408. if (more.length === 0) return;
  409. below = more.offset().top - results.offset().top - results.height();
  410. if (below <= 0) {
  411. more.addClass("select2-active");
  412. this.opts.query({term: this.search.val(), page: page, callback: this.bind(function (data) {
  413. var parts = [], self = this;
  414. $(data.results).each(function () {
  415. parts.push("<li class='select2-result'>");
  416. parts.push(self.opts.formatResult(this));
  417. parts.push("</li>");
  418. });
  419. more.before(parts.join(""));
  420. results.find(".select2-result").each(function (i) {
  421. var e = $(this);
  422. if (e.data("select2-data") !== undefined) {
  423. offset = i;
  424. } else {
  425. e.data("select2-data", data.results[i - offset - 1]);
  426. }
  427. });
  428. if (data.more) {
  429. more.removeClass("select2-active");
  430. } else {
  431. more.remove();
  432. }
  433. this.resultsPage = page;
  434. })});
  435. }
  436. };
  437. /**
  438. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  439. */
  440. AbstractSelect2.prototype.updateResults = function (initial) {
  441. var search = this.search, results = this.results, opts = this.opts;
  442. search.addClass("select2-active");
  443. function render(html) {
  444. results.html(html);
  445. results.scrollTop(0);
  446. search.removeClass("select2-active");
  447. }
  448. if (search.val().length < opts.minimumInputLength) {
  449. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  450. return;
  451. }
  452. this.resultsPage = 1;
  453. opts.query({term: search.val(), page: this.resultsPage, callback: this.bind(function (data) {
  454. var parts = []; // html parts
  455. if (data.results.length === 0) {
  456. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  457. return;
  458. }
  459. $(data.results).each(function () {
  460. parts.push("<li class='select2-result'>");
  461. parts.push(opts.formatResult(this));
  462. parts.push("</li>");
  463. });
  464. if (data.more === true) {
  465. parts.push("<li class='select2-more-results'>Loading more results...</li>");
  466. }
  467. render(parts.join(""));
  468. results.children(".select2-result").each(function (i) {
  469. var d = data.results[i];
  470. $(this).data("select2-data", d);
  471. });
  472. this.postprocessResults(data, initial);
  473. })});
  474. };
  475. AbstractSelect2.prototype.cancel = function () {
  476. this.close();
  477. };
  478. AbstractSelect2.prototype.blur = function () {
  479. /* we do this in a timeout so that current event processing can complete before this code is executed.
  480. this allows tab index to be preserved even if this code blurs the textfield */
  481. window.setTimeout(this.bind(function () {
  482. this.close();
  483. this.container.removeClass("select2-container-active");
  484. this.clearSearch();
  485. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  486. this.search.blur();
  487. }), 10);
  488. };
  489. AbstractSelect2.prototype.focusSearch = function () {
  490. /* we do this in a timeout so that current event processing can complete before this code is executed.
  491. this makes sure the search field is focussed even if the current event would blur it */
  492. window.setTimeout(this.bind(function () {
  493. this.search.focus();
  494. }), 10);
  495. };
  496. AbstractSelect2.prototype.selectHighlighted = function () {
  497. var data = this.results.find(".select2-highlighted:not(.select2-disabled)").data("select2-data");
  498. if (data) {
  499. this.onSelect(data);
  500. }
  501. };
  502. AbstractSelect2.prototype.getPlaceholder = function () {
  503. var placeholder = this.opts.element.data("placeholder");
  504. if (placeholder !== undefined) return placeholder;
  505. return this.opts.placeholder;
  506. };
  507. function SingleSelect2() {
  508. }
  509. SingleSelect2.prototype = new AbstractSelect2();
  510. SingleSelect2.prototype.constructor = SingleSelect2;
  511. SingleSelect2.prototype.parent = AbstractSelect2.prototype;
  512. SingleSelect2.prototype.createContainer = function () {
  513. return $("<div></div>", {
  514. "class": "select2-container",
  515. "style": "width: " + this.opts.element.outerWidth() + "px"
  516. }).html([
  517. " <a href='javascript:void(0)' class='select2-choice'>",
  518. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  519. " <div><b></b></div>" ,
  520. "</a>",
  521. " <div class='select2-drop' style='display:none;'>" ,
  522. " <div class='select2-search'>" ,
  523. " <input type='text' autocomplete='off'/>" ,
  524. " </div>" ,
  525. " <ul class='select2-results'>" ,
  526. " </ul>" ,
  527. "</div>"].join(""));
  528. };
  529. SingleSelect2.prototype.open = function () {
  530. var width;
  531. if (this.opened()) return;
  532. this.parent.open.apply(this, arguments);
  533. // size the search field
  534. width = this.dropdown.width();
  535. width -= getSideBorderPadding(this.container.find(".select2-search"));
  536. width -= getSideBorderPadding(this.search);
  537. this.search.css({width: width});
  538. };
  539. SingleSelect2.prototype.close = function () {
  540. if (!this.opened()) return;
  541. this.parent.close.apply(this, arguments);
  542. };
  543. SingleSelect2.prototype.cancel = function () {
  544. this.parent.cancel.apply(this, arguments);
  545. this.selection.focus();
  546. };
  547. SingleSelect2.prototype.initContainer = function () {
  548. var selection, container = this.container, clickingInside = false,
  549. selector = ".select2-choice", selected;
  550. this.selection = selection = container.find(selector);
  551. this.search.bind("keydown", this.bind(function (e) {
  552. switch (e.which) {
  553. case KEY.UP:
  554. case KEY.DOWN:
  555. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  556. killEvent(e);
  557. return;
  558. case KEY.TAB:
  559. case KEY.ENTER:
  560. this.selectHighlighted();
  561. killEvent(e);
  562. return;
  563. case KEY.ESC:
  564. this.cancel(e);
  565. e.preventDefault();
  566. return;
  567. }
  568. }));
  569. container.delegate(selector, "click", this.bind(function (e) {
  570. clickingInside = true;
  571. if (this.opened()) {
  572. this.close();
  573. selection.focus();
  574. } else {
  575. this.open();
  576. }
  577. e.preventDefault();
  578. clickingInside = false;
  579. }));
  580. container.delegate(selector, "keydown", this.bind(function (e) {
  581. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  582. return;
  583. }
  584. this.open();
  585. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN || e.which === KEY.SPACE) {
  586. // prevent the page from scrolling
  587. killEvent(e);
  588. }
  589. if (e.which === KEY.ENTER) {
  590. // do not propagate the event otherwise we open, and propagate enter which closes
  591. killEvent(e);
  592. }
  593. }));
  594. container.delegate(selector, "focus", function () { container.addClass("select2-container-active"); });
  595. container.delegate(selector, "blur", this.bind(function () {
  596. if (clickingInside) return;
  597. if (!this.opened()) this.blur();
  598. }));
  599. selection.delegate("abbr", "click", this.bind(function (e) {
  600. this.val("");
  601. killEvent(e);
  602. this.close();
  603. }));
  604. if (this.select) {
  605. selected = this.select.find(":selected");
  606. this.updateSelection({id: selected.attr("value"), text: selected.text()});
  607. }
  608. this.setPlaceholder();
  609. };
  610. SingleSelect2.prototype.setPlaceholder = function () {
  611. var placeholder = this.getPlaceholder();
  612. if (this.opts.element.val() === "" && placeholder !== undefined) {
  613. // check for a first blank option if attached to a select
  614. if (this.select && this.select.find("option:first").text() !== "") return;
  615. if (typeof(placeholder) === "object") {
  616. this.updateSelection(placeholder);
  617. } else {
  618. this.selection.find("span").html(placeholder);
  619. }
  620. this.selection.addClass("select2-default");
  621. this.selection.find("abbr").hide();
  622. }
  623. };
  624. SingleSelect2.prototype.postprocessResults = function (data, initial) {
  625. var selected = 0, self = this;
  626. // find the selected element in the result list
  627. this.results.find(".select2-result").each(function (i) {
  628. if ($(this).data("select2-data").id === self.opts.element.val()) {
  629. selected = i;
  630. return false;
  631. }
  632. });
  633. // and highlight it
  634. this.highlight(selected);
  635. // hide the search box if this is the first we got the results and there are a few of them
  636. if (initial === true) {
  637. this.search.toggle(data.results.length >= this.opts.minimumResultsForSearch);
  638. }
  639. };
  640. SingleSelect2.prototype.onSelect = function (data) {
  641. this.opts.element.val(data.id);
  642. this.updateSelection(data);
  643. this.close();
  644. this.selection.focus();
  645. };
  646. SingleSelect2.prototype.updateSelection = function (data) {
  647. this.selection
  648. .find("span")
  649. .html(this.opts.formatSelection(data))
  650. .removeClass("select2-default");
  651. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  652. this.selection.find("abbr").show();
  653. }
  654. };
  655. SingleSelect2.prototype.val = function () {
  656. var val, data = null;
  657. if (arguments.length === 0) {
  658. return this.opts.element.val();
  659. }
  660. val = arguments[0];
  661. if (this.select) {
  662. // val is an id
  663. this.select
  664. .val(val)
  665. .find(":selected").each(function () {
  666. data = {id: $(this).attr("value"), text: $(this).text()};
  667. return false;
  668. });
  669. this.updateSelection(data);
  670. } else {
  671. // val is an object
  672. this.opts.element.val((val === null) ? "" : val.id);
  673. this.updateSelection(val);
  674. }
  675. this.setPlaceholder();
  676. };
  677. SingleSelect2.prototype.clearSearch = function () {
  678. this.search.val("");
  679. };
  680. function MultiSelect2(opts) {
  681. }
  682. MultiSelect2.prototype = new AbstractSelect2();
  683. MultiSelect2.prototype.constructor = AbstractSelect2;
  684. MultiSelect2.prototype.parent = AbstractSelect2.prototype;
  685. MultiSelect2.prototype.createContainer = function () {
  686. return $("<div></div>", {
  687. "class": "select2-container select2-container-multi",
  688. "style": "width: " + this.opts.element.outerWidth() + "px"
  689. }).html([
  690. " <ul class='select2-choices'>",
  691. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  692. " <li class='select2-search-field'>" ,
  693. " <input type='text' autocomplete='off' style='width: 25px;'>" ,
  694. " </li>" ,
  695. "</ul>" ,
  696. "<div class='select2-drop' style='display:none;'>" ,
  697. " <ul class='select2-results'>" ,
  698. " </ul>" ,
  699. "</div>"].join(""));
  700. };
  701. MultiSelect2.prototype.initContainer = function () {
  702. var selector = ".select2-choices", selection, data;
  703. this.searchContainer = this.container.find(".select2-search-field");
  704. this.selection = selection = this.container.find(selector);
  705. this.search.bind("keydown", this.bind(function (e) {
  706. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  707. this.close();
  708. var choices,
  709. selected = this.selection.find(".select2-search-choice-focus");
  710. if (selected.length > 0) {
  711. this.unselect(selected.first());
  712. this.search.width(10);
  713. killEvent(e);
  714. return;
  715. }
  716. choices = this.selection.find(".select2-search-choice");
  717. if (choices.length > 0) {
  718. choices.last().addClass("select2-search-choice-focus");
  719. }
  720. } else {
  721. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  722. }
  723. if (this.opened()) {
  724. switch (e.which) {
  725. case KEY.UP:
  726. case KEY.DOWN:
  727. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  728. killEvent(e);
  729. return;
  730. case KEY.ENTER:
  731. this.selectHighlighted();
  732. killEvent(e);
  733. return;
  734. case KEY.ESC:
  735. this.cancel(e);
  736. e.preventDefault();
  737. return;
  738. }
  739. }
  740. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  741. return;
  742. }
  743. this.open();
  744. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  745. // prevent the page from scrolling
  746. killEvent(e);
  747. }
  748. }));
  749. this.search.bind("keyup", this.bind(this.resizeSearch));
  750. this.container.delegate(selector, "click", this.bind(function (e) {
  751. if (this.select) {
  752. this.open();
  753. }
  754. this.focusSearch();
  755. e.preventDefault();
  756. }));
  757. this.container.delegate(selector, "focus", this.bind(function () {
  758. this.container.addClass("select2-container-active");
  759. this.clearPlaceholder();
  760. }));
  761. if (this.select) {
  762. data = [];
  763. this.select.find(":selected").each(function () {
  764. data.push({id: $(this).attr("value"), text: $(this).text()});
  765. });
  766. this.updateSelection(data);
  767. }
  768. // set the placeholder if necessary
  769. this.clearSearch();
  770. };
  771. MultiSelect2.prototype.clearSearch = function () {
  772. var placeholder = this.getPlaceholder();
  773. this.search.val("").width(10);
  774. if (placeholder !== undefined && this.getVal().length === 0) {
  775. this.search.val(placeholder).addClass("select2-default");
  776. this.resizeSearch();
  777. }
  778. };
  779. MultiSelect2.prototype.clearPlaceholder = function () {
  780. if (this.search.hasClass("select2-default")) {
  781. this.search.val("").removeClass("select2-default");
  782. }
  783. };
  784. MultiSelect2.prototype.open = function () {
  785. if (this.opened()) return;
  786. this.parent.open.apply(this, arguments);
  787. this.resizeSearch();
  788. this.focusSearch();
  789. };
  790. MultiSelect2.prototype.close = function () {
  791. if (!this.opened()) return;
  792. this.parent.close.apply(this, arguments);
  793. };
  794. MultiSelect2.prototype.updateSelection = function (data) {
  795. var self = this;
  796. this.selection.find(".select2-search-choice").remove();
  797. $(data).each(function () {
  798. self.addSelectedChoice(this);
  799. });
  800. self.postprocessResults();
  801. this.alignDropdown();
  802. };
  803. MultiSelect2.prototype.onSelect = function (data) {
  804. this.addSelectedChoice(data);
  805. if (this.select) { this.postprocessResults(); }
  806. this.close();
  807. this.search.width(10);
  808. this.focusSearch();
  809. };
  810. MultiSelect2.prototype.cancel = function () {
  811. this.close();
  812. this.focusSearch();
  813. };
  814. MultiSelect2.prototype.addSelectedChoice = function (data) {
  815. var choice,
  816. id = data.id,
  817. parts,
  818. val = this.getVal();
  819. parts = ["<li class='select2-search-choice'>",
  820. this.opts.formatSelection(data),
  821. "<a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>",
  822. "</li>"
  823. ];
  824. choice = $(parts.join(""));
  825. choice.find("a")
  826. .bind("click dblclick", this.bind(function (e) {
  827. this.unselect($(e.target));
  828. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  829. killEvent(e);
  830. this.close();
  831. this.focusSearch();
  832. })).bind("focus", this.bind(function () {
  833. this.container.addClass("select2-container-active");
  834. }));
  835. choice.data("select2-data", data);
  836. choice.insertBefore(this.searchContainer);
  837. val.push(id);
  838. this.setVal(val);
  839. };
  840. MultiSelect2.prototype.unselect = function (selected) {
  841. var val = this.getVal(),
  842. index;
  843. selected = selected.closest(".select2-search-choice");
  844. if (selected.length === 0) {
  845. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  846. }
  847. index = indexOf(selected.data("select2-data").id, val);
  848. if (index >= 0) {
  849. val.splice(index, 1);
  850. this.setVal(val);
  851. if (this.select) this.postprocessResults();
  852. }
  853. selected.remove();
  854. window.setTimeout(this.bind(this.alignDropdown), 20);
  855. };
  856. MultiSelect2.prototype.postprocessResults = function () {
  857. var val = this.getVal(),
  858. choices = this.results.find(".select2-result"),
  859. self = this;
  860. choices.each(function () {
  861. var choice = $(this), id = choice.data("select2-data").id;
  862. if (val.indexOf(id) >= 0) {
  863. choice.addClass("select2-disabled");
  864. } else {
  865. choice.removeClass("select2-disabled");
  866. }
  867. });
  868. choices.each(function (i) {
  869. if (!$(this).hasClass("select2-disabled")) {
  870. self.highlight(i);
  871. return false;
  872. }
  873. });
  874. };
  875. MultiSelect2.prototype.resizeSearch = function () {
  876. var minimumWidth, left, maxWidth, containerLeft, searchWidth;
  877. minimumWidth = measureTextWidth(this.search) + 10;
  878. left = this.search.offset().left;
  879. maxWidth = this.selection.width();
  880. containerLeft = this.selection.offset().left;
  881. searchWidth = maxWidth - (left - containerLeft) - getSideBorderPadding(this.search);
  882. if (searchWidth < minimumWidth) {
  883. searchWidth = maxWidth - getSideBorderPadding(this.search);
  884. }
  885. if (searchWidth < 40) {
  886. searchWidth = maxWidth - getSideBorderPadding(this.search);
  887. }
  888. this.search.width(searchWidth);
  889. };
  890. MultiSelect2.prototype.getVal = function () {
  891. var val;
  892. if (this.select) {
  893. val = this.select.val();
  894. return val === null ? [] : val;
  895. } else {
  896. val = this.opts.element.val();
  897. return (val === null || val === "") ? [] : val.split(",");
  898. }
  899. };
  900. MultiSelect2.prototype.setVal = function (val) {
  901. if (this.select) {
  902. this.select.val(val);
  903. } else {
  904. this.opts.element.val(val.length === 0 ? "" : val.join(","));
  905. }
  906. };
  907. MultiSelect2.prototype.val = function () {
  908. var val, data = [];
  909. if (arguments.length === 0) {
  910. return this.getVal();
  911. }
  912. val = arguments[0];
  913. if (this.select) {
  914. // val is a list of ids
  915. this.setVal(val);
  916. this.select.find(":selected").each(function () {
  917. data.push({id: $(this).attr("value"), text: $(this).text()});
  918. });
  919. this.updateSelection(data);
  920. } else {
  921. val = (val === null) ? [] : val;
  922. this.setVal(val);
  923. // val is a list of objects
  924. $(val).each(function () { data.push(this.id); });
  925. this.setVal(data);
  926. this.updateSelection(val);
  927. }
  928. };
  929. $.fn.select2 = function () {
  930. var args = Array.prototype.slice.call(arguments, 0),
  931. opts,
  932. select2,
  933. value, multiple, allowedMethods = ["val"];
  934. this.each(function () {
  935. if (args.length === 0 || typeof(args[0]) === "object") {
  936. opts = args.length === 0 ? {} : args[0];
  937. opts.element = $(this);
  938. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  939. multiple = opts.element.attr("multiple");
  940. } else {
  941. multiple = opts.multiple || false;
  942. }
  943. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  944. select2.init(opts);
  945. } else if (typeof(args[0]) === "string") {
  946. if (indexOf(args[0], allowedMethods) < 0) {
  947. throw "Unknown method: " + args[0];
  948. }
  949. value = undefined;
  950. select2 = $(this).data("select2");
  951. value = select2[args[0]].apply(select2, args.slice(1));
  952. if (value !== undefined) {return false;}
  953. } else {
  954. throw "Invalid arguments to select2 plugin: " + args;
  955. }
  956. });
  957. return (value === undefined) ? this : value;
  958. };
  959. }(jQuery));