select2.js 37 KB

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