select2.js 38 KB

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