select2.js 37 KB

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