select2.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. /*
  2. Copyright 2012 Igor Vaynberg
  3. Version: 2.1 Timestamp: Tue Jun 12 19:50:25 PDT 2012
  4. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in
  5. compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software distributed under the License is
  8. distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and limitations under the License.
  10. */
  11. (function ($, undefined) {
  12. "use strict";
  13. /*global document, window, jQuery, console */
  14. if (window.Select2 !== undefined) {
  15. return;
  16. }
  17. var KEY, AbstractSelect2, SingleSelect2, MultiSelect2;
  18. KEY = {
  19. TAB: 9,
  20. ENTER: 13,
  21. ESC: 27,
  22. SPACE: 32,
  23. LEFT: 37,
  24. UP: 38,
  25. RIGHT: 39,
  26. DOWN: 40,
  27. SHIFT: 16,
  28. CTRL: 17,
  29. ALT: 18,
  30. PAGE_UP: 33,
  31. PAGE_DOWN: 34,
  32. HOME: 36,
  33. END: 35,
  34. BACKSPACE: 8,
  35. DELETE: 46,
  36. isArrow: function (k) {
  37. k = k.which ? k.which : k;
  38. switch (k) {
  39. case KEY.LEFT:
  40. case KEY.RIGHT:
  41. case KEY.UP:
  42. case KEY.DOWN:
  43. return true;
  44. }
  45. return false;
  46. },
  47. isControl: function (k) {
  48. k = k.which ? k.which : k;
  49. switch (k) {
  50. case KEY.SHIFT:
  51. case KEY.CTRL:
  52. case KEY.ALT:
  53. return true;
  54. }
  55. return false;
  56. },
  57. isFunctionKey: function (k) {
  58. k = k.which ? k.which : k;
  59. return k >= 112 && k <= 123;
  60. }
  61. };
  62. function indexOf(value, array) {
  63. var i = 0, l = array.length, v;
  64. if (typeof value === "undefined") {
  65. return -1;
  66. }
  67. if (value.constructor === String) {
  68. for (; i < l; i = i + 1) if (value.localeCompare(array[i]) === 0) return i;
  69. } else {
  70. for (; i < l; i = i + 1) {
  71. v = array[i];
  72. if (v.constructor === String) {
  73. if (v.localeCompare(value) === 0) return i;
  74. } else {
  75. if (v === value) return i;
  76. }
  77. }
  78. }
  79. return -1;
  80. }
  81. /**
  82. * Compares equality of a and b taking into account that a and b may be strings, in which case localCompare is used
  83. * @param a
  84. * @param b
  85. */
  86. function equal(a, b) {
  87. if (a === b) return true;
  88. if (a === undefined || b === undefined) return false;
  89. if (a === null || b === null) return false;
  90. if (a.constructor === String) return a.localeCompare(b) === 0;
  91. if (b.constructor === String) return b.localeCompare(a) === 0;
  92. return false;
  93. }
  94. /**
  95. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  96. * strings
  97. * @param string
  98. * @param separator
  99. */
  100. function splitVal(string, separator) {
  101. var val, i, l;
  102. if (string === null || string.length < 1) return [];
  103. val = string.split(separator);
  104. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  105. return val;
  106. }
  107. function getSideBorderPadding(element) {
  108. return element.outerWidth() - element.width();
  109. }
  110. function installKeyUpChangeEvent(element) {
  111. element.bind("keydown", function () {
  112. element.data("keyup-change-value", element.val());
  113. });
  114. element.bind("keyup", function () {
  115. if (element.val() !== element.data("keyup-change-value")) {
  116. element.trigger("keyup-change");
  117. }
  118. });
  119. }
  120. /**
  121. * filters mouse events so an event is fired only if the mouse moved.
  122. *
  123. * filters out mouse events that occur when mouse is stationary but
  124. * the elements under the pointer are scrolled.
  125. */
  126. $(document).delegate("*", "mousemove", function (e) {
  127. $(document).data("select2-lastpos", {x: e.pageX, y: e.pageY});
  128. });
  129. function installFilteredMouseMove(element) {
  130. element.bind("mousemove", function (e) {
  131. var lastpos = $(document).data("select2-lastpos");
  132. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  133. $(e.target).trigger("mousemove-filtered", e);
  134. }
  135. });
  136. }
  137. /**
  138. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  139. * within the last quietMillis milliseconds.
  140. *
  141. * @param quietMillis number of milliseconds to wait before invoking fn
  142. * @param fn function to be debounced
  143. * @return debounced version of fn
  144. */
  145. function debounce(quietMillis, fn) {
  146. var timeout;
  147. return function () {
  148. window.clearTimeout(timeout);
  149. timeout = window.setTimeout(fn, quietMillis);
  150. };
  151. }
  152. function installDebouncedScroll(threshold, element) {
  153. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  154. element.bind("scroll", function (e) {
  155. if (indexOf(e.target, element.get()) >= 0) notify(e);
  156. });
  157. }
  158. function killEvent(event) {
  159. event.preventDefault();
  160. event.stopPropagation();
  161. }
  162. function measureTextWidth(e) {
  163. var sizer, width;
  164. sizer = $("<div></div>").css({
  165. position: "absolute",
  166. left: "-1000px",
  167. top: "-1000px",
  168. display: "none",
  169. fontSize: e.css("fontSize"),
  170. fontFamily: e.css("fontFamily"),
  171. fontStyle: e.css("fontStyle"),
  172. fontWeight: e.css("fontWeight"),
  173. letterSpacing: e.css("letterSpacing"),
  174. textTransform: e.css("textTransform"),
  175. whiteSpace: "nowrap"
  176. });
  177. sizer.text(e.val());
  178. $("body").append(sizer);
  179. width = sizer.width();
  180. sizer.remove();
  181. return width;
  182. }
  183. /**
  184. * Produces an ajax-based query function
  185. *
  186. * @param options object containing configuration paramters
  187. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  188. * @param options.url url for the data
  189. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  190. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
  191. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  192. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  193. * The expected format is an object containing the following keys:
  194. * results array of objects that will be used as choices
  195. * more (optional) boolean indicating whether there are more results available
  196. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  197. */
  198. function ajax(options) {
  199. var timeout, // current scheduled but not yet executed request
  200. requestSequence = 0, // sequence used to drop out-of-order responses
  201. handler = null,
  202. quietMillis = options.quietMillis || 100;
  203. return function (query) {
  204. window.clearTimeout(timeout);
  205. timeout = window.setTimeout(function () {
  206. requestSequence += 1; // increment the sequence
  207. var requestNumber = requestSequence, // this request's sequence number
  208. data = options.data, // ajax data function
  209. transport = options.transport || $.ajax;
  210. data = data.call(this, query.term, query.page, query.context);
  211. if( null !== handler){
  212. handler.abort();
  213. }
  214. handler = transport.call(null, {
  215. url: options.url,
  216. dataType: options.dataType,
  217. data: data,
  218. success: function (data) {
  219. if (requestNumber < requestSequence) {
  220. return;
  221. }
  222. // TODO 3.0 - replace query.page with query so users have access to term, page, etc.
  223. var results = options.results(data, query.page);
  224. query.callback(results);
  225. }
  226. });
  227. }, quietMillis);
  228. };
  229. }
  230. /**
  231. * Produces a query function that works with a local array
  232. *
  233. * @param options object containing configuration parameters. The options parameter can either be an array or an
  234. * object.
  235. *
  236. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  237. *
  238. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  239. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  240. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  241. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  242. * the text.
  243. */
  244. function local(options) {
  245. var data = options, // data elements
  246. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  247. if (!$.isArray(data)) {
  248. text = data.text;
  249. // if text is not a function we assume it to be a key name
  250. if (!$.isFunction(text)) text = function (item) { return item[data.text]; };
  251. data = data.results;
  252. }
  253. return function (query) {
  254. var t = query.term, filtered = {};
  255. if (t === "") {
  256. query.callback({results: data});
  257. return;
  258. }
  259. filtered.results = $(data)
  260. .filter(function () {return query.matcher(t, text(this));})
  261. .get();
  262. query.callback(filtered);
  263. };
  264. }
  265. // TODO javadoc
  266. function tags(data) {
  267. // TODO even for a function we should probably return a wrapper that does the same object/string check as
  268. // the function for arrays. otherwise only functions that return objects are supported.
  269. if ($.isFunction(data)) {
  270. return data;
  271. }
  272. // if not a function we assume it to be an array
  273. return function (query) {
  274. var t = query.term, filtered = {results: []};
  275. $(data).each(function () {
  276. var isObject = this.text !== undefined,
  277. text = isObject ? this.text : this;
  278. if (t === "" || query.matcher(t, text)) {
  279. filtered.results.push(isObject ? this : {id: this, text: this});
  280. }
  281. });
  282. query.callback(filtered);
  283. };
  284. }
  285. /**
  286. * blurs any Select2 container that has focus when an element outside them was clicked or received focus
  287. */
  288. $(document).ready(function () {
  289. $(document).delegate("*", "mousedown focusin touchend", function (e) {
  290. var target = $(e.target).closest("div.select2-container").get(0);
  291. $(document).find("div.select2-container-active").each(function () {
  292. if (this !== target) $(this).data("select2").blur();
  293. });
  294. });
  295. });
  296. /**
  297. * Creates a new class
  298. *
  299. * @param superClass
  300. * @param methods
  301. */
  302. function clazz(SuperClass, methods) {
  303. var constructor = function () {};
  304. constructor.prototype = new SuperClass;
  305. constructor.prototype.constructor = constructor;
  306. constructor.prototype.parent = SuperClass.prototype;
  307. constructor.prototype = $.extend(constructor.prototype, methods);
  308. return constructor;
  309. }
  310. AbstractSelect2 = clazz(Object, {
  311. bind: function (func) {
  312. var self = this;
  313. return function () {
  314. func.apply(self, arguments);
  315. };
  316. },
  317. init: function (opts) {
  318. var results, search, resultsSelector = ".select2-results";
  319. // prepare options
  320. this.opts = opts = this.prepareOpts(opts);
  321. this.id=opts.id;
  322. // destroy if called on an existing component
  323. if (opts.element.data("select2") !== undefined &&
  324. opts.element.data("select2") !== null) {
  325. this.destroy();
  326. }
  327. this.enabled=true;
  328. this.container = this.createContainer();
  329. if (opts.element.attr("class") !== undefined) {
  330. this.container.addClass(opts.element.attr("class"));
  331. }
  332. // swap container for the element
  333. this.opts.element
  334. .data("select2", this)
  335. .hide()
  336. .after(this.container);
  337. this.container.data("select2", this);
  338. this.dropdown = this.container.find(".select2-drop");
  339. this.results = results = this.container.find(resultsSelector);
  340. this.search = search = this.container.find("input[type=text]");
  341. this.resultsPage = 0;
  342. this.context = null;
  343. // initialize the container
  344. this.initContainer();
  345. installFilteredMouseMove(this.results);
  346. this.container.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
  347. installDebouncedScroll(80, this.results);
  348. this.container.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  349. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  350. if ($.fn.mousewheel) {
  351. results.mousewheel(function (e, delta, deltaX, deltaY) {
  352. var top = results.scrollTop(), height;
  353. if (deltaY > 0 && top - deltaY <= 0) {
  354. results.scrollTop(0);
  355. killEvent(e);
  356. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  357. results.scrollTop(results.get(0).scrollHeight - results.height());
  358. killEvent(e);
  359. }
  360. });
  361. }
  362. installKeyUpChangeEvent(search);
  363. search.bind("keyup-change", this.bind(this.updateResults));
  364. search.bind("focus", function () { search.addClass("select2-focused");});
  365. search.bind("blur", function () { search.removeClass("select2-focused");});
  366. this.container.delegate(resultsSelector, "click", this.bind(function (e) {
  367. if ($(e.target).closest(".select2-result:not(.select2-disabled)").length > 0) {
  368. this.highlightUnderEvent(e);
  369. this.selectHighlighted(e);
  370. } else {
  371. killEvent(e);
  372. this.focusSearch();
  373. }
  374. }));
  375. if ($.isFunction(this.opts.initSelection)) {
  376. // initialize selection based on the current value of the source element
  377. this.initSelection();
  378. // if the user has provided a function that can set selection based on the value of the source element
  379. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  380. this.monitorSource();
  381. }
  382. if (opts.element.is(":disabled")) this.disable();
  383. },
  384. destroy: function () {
  385. var select2 = this.opts.element.data("select2");
  386. if (select2 !== undefined) {
  387. select2.container.remove();
  388. select2.opts.element
  389. .removeData("select2")
  390. .unbind(".select2")
  391. .show();
  392. }
  393. },
  394. prepareOpts: function (opts) {
  395. var element, select, idKey;
  396. element = opts.element;
  397. if (element.get(0).tagName.toLowerCase() === "select") {
  398. this.select = select = opts.element;
  399. }
  400. if (select) {
  401. // these options are not allowed when attached to a select because they are picked up off the element itself
  402. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  403. if (this in opts) {
  404. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  405. }
  406. });
  407. }
  408. opts = $.extend({}, {
  409. formatResult: function (data) { return data.text; },
  410. formatSelection: function (data) { return data.text; },
  411. formatNoMatches: function () { return "No matches found"; },
  412. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  413. minimumResultsForSearch: 0,
  414. minimumInputLength: 0,
  415. id: function (e) { return e.id; },
  416. matcher: function(term, text) {
  417. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  418. }
  419. }, opts);
  420. if (typeof(opts.id) !== "function") {
  421. idKey = opts.id;
  422. opts.id = function (e) { return e[idKey]; };
  423. }
  424. if (select) {
  425. opts.query = this.bind(function (query) {
  426. var data = {results: [], more: false},
  427. term = query.term,
  428. placeholder = this.getPlaceholder();
  429. element.find("option").each(function (i) {
  430. var e = $(this),
  431. text = e.text();
  432. if (i === 0 && placeholder !== undefined && text === "") return true;
  433. if (query.matcher(term, text)) {
  434. data.results.push({id: e.attr("value"), text: text});
  435. }
  436. });
  437. query.callback(data);
  438. });
  439. // this is needed because inside val() we construct choices from options and there id is hardcoded
  440. opts.id=function(e) { return e.id; };
  441. } else {
  442. if (!("query" in opts)) {
  443. if ("ajax" in opts) {
  444. opts.query = ajax(opts.ajax);
  445. } else if ("data" in opts) {
  446. opts.query = local(opts.data);
  447. } else if ("tags" in opts) {
  448. opts.query = tags(opts.tags);
  449. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  450. opts.initSelection = function (element) {
  451. var data = [];
  452. $(splitVal(element.val(), ",")).each(function () {
  453. data.push({id: this, text: this});
  454. });
  455. return data;
  456. };
  457. }
  458. }
  459. }
  460. if (typeof(opts.query) !== "function") {
  461. throw "query function not defined for Select2 " + opts.element.attr("id");
  462. }
  463. return opts;
  464. },
  465. /**
  466. * Monitor the original element for changes and update select2 accordingly
  467. */
  468. monitorSource: function () {
  469. this.opts.element.bind("change.select2", this.bind(function (e) {
  470. if (this.opts.element.data("select2-change-triggered") !== true) {
  471. this.initSelection();
  472. }
  473. }));
  474. },
  475. /**
  476. * Triggers the change event on the source element
  477. */
  478. triggerChange: function () {
  479. // Prevents recursive triggering
  480. this.opts.element.data("select2-change-triggered", true);
  481. this.opts.element.trigger("change");
  482. this.opts.element.data("select2-change-triggered", false);
  483. },
  484. enable: function() {
  485. if (this.enabled) return;
  486. this.enabled=true;
  487. this.container.removeClass("select2-container-disabled");
  488. },
  489. disable: function() {
  490. if (!this.enabled) return;
  491. this.close();
  492. this.enabled=false;
  493. this.container.addClass("select2-container-disabled");
  494. },
  495. opened: function () {
  496. return this.container.hasClass("select2-dropdown-open");
  497. },
  498. open: function () {
  499. if (this.opened()) return;
  500. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  501. this.updateResults(true);
  502. this.dropdown.show();
  503. this.ensureHighlightVisible();
  504. this.focusSearch();
  505. },
  506. close: function () {
  507. if (!this.opened()) return;
  508. this.dropdown.hide();
  509. this.container.removeClass("select2-dropdown-open");
  510. this.results.empty();
  511. this.clearSearch();
  512. },
  513. clearSearch: function () {
  514. },
  515. ensureHighlightVisible: function () {
  516. var results = this.results, children, index, child, hb, rb, y, more;
  517. children = results.children(".select2-result");
  518. index = this.highlight();
  519. if (index < 0) return;
  520. child = $(children[index]);
  521. hb = child.offset().top + child.outerHeight();
  522. // if this is the last child lets also make sure select2-more-results is visible
  523. if (index === children.length - 1) {
  524. more = results.find("li.select2-more-results");
  525. if (more.length > 0) {
  526. hb = more.offset().top + more.outerHeight();
  527. }
  528. }
  529. rb = results.offset().top + results.outerHeight();
  530. if (hb > rb) {
  531. results.scrollTop(results.scrollTop() + (hb - rb));
  532. }
  533. y = child.offset().top - results.offset().top;
  534. // make sure the top of the element is visible
  535. if (y < 0) {
  536. results.scrollTop(results.scrollTop() + y); // y is negative
  537. }
  538. },
  539. moveHighlight: function (delta) {
  540. var choices = this.results.children(".select2-result"),
  541. index = this.highlight();
  542. while (index > -1 && index < choices.length) {
  543. index += delta;
  544. if (!$(choices[index]).hasClass("select2-disabled")) {
  545. this.highlight(index);
  546. break;
  547. }
  548. }
  549. },
  550. highlight: function (index) {
  551. var choices = this.results.children(".select2-result");
  552. if (arguments.length === 0) {
  553. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  554. }
  555. choices.removeClass("select2-highlighted");
  556. if (index >= choices.length) index = choices.length - 1;
  557. if (index < 0) index = 0;
  558. $(choices[index]).addClass("select2-highlighted");
  559. this.ensureHighlightVisible();
  560. if (this.opened()) this.focusSearch();
  561. },
  562. highlightUnderEvent: function (event) {
  563. var el = $(event.target).closest(".select2-result");
  564. if (el.length > 0) {
  565. this.highlight(el.index());
  566. }
  567. },
  568. loadMoreIfNeeded: function () {
  569. var results = this.results,
  570. more = results.find("li.select2-more-results"),
  571. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  572. offset = -1, // index of first element without data
  573. page = this.resultsPage + 1;
  574. if (more.length === 0) return;
  575. below = more.offset().top - results.offset().top - results.height();
  576. if (below <= 0) {
  577. more.addClass("select2-active");
  578. this.opts.query({
  579. term: this.search.val(),
  580. page: page,
  581. context: this.context,
  582. matcher: this.opts.matcher,
  583. callback: this.bind(function (data) {
  584. var parts = [], self = this;
  585. $(data.results).each(function () {
  586. parts.push("<li class='select2-result'>");
  587. parts.push(self.opts.formatResult(this));
  588. parts.push("</li>");
  589. });
  590. more.before(parts.join(""));
  591. results.find(".select2-result").each(function (i) {
  592. var e = $(this);
  593. if (e.data("select2-data") !== undefined) {
  594. offset = i;
  595. } else {
  596. e.data("select2-data", data.results[i - offset - 1]);
  597. }
  598. });
  599. if (data.more) {
  600. more.removeClass("select2-active");
  601. } else {
  602. more.remove();
  603. }
  604. this.resultsPage = page;
  605. })});
  606. }
  607. },
  608. /**
  609. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  610. */
  611. updateResults: function (initial) {
  612. var search = this.search, results = this.results, opts = this.opts, self=this;
  613. // if the search is currently hidden we do not alter the results
  614. if (initial !== true && this.showSearchInput === false) {
  615. return;
  616. }
  617. search.addClass("select2-active");
  618. function render(html) {
  619. results.html(html);
  620. results.scrollTop(0);
  621. search.removeClass("select2-active");
  622. }
  623. if (search.val().length < opts.minimumInputLength) {
  624. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  625. return;
  626. }
  627. this.resultsPage = 1;
  628. opts.query({
  629. term: search.val(),
  630. page: this.resultsPage,
  631. context: null,
  632. matcher: opts.matcher,
  633. callback: this.bind(function (data) {
  634. var parts = [], // html parts
  635. def; // default choice
  636. // save context, if any
  637. this.context = (data.context===undefined) ? null : data.context;
  638. // create a default choice and prepend it to the list
  639. if (this.opts.createSearchChoice && search.val() !== "") {
  640. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  641. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  642. if ($(data.results).filter(
  643. function () {
  644. return equal(self.id(this), self.id(def));
  645. }).length === 0) {
  646. data.results.unshift(def);
  647. }
  648. }
  649. }
  650. if (data.results.length === 0) {
  651. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  652. return;
  653. }
  654. $(data.results).each(function () {
  655. parts.push("<li class='select2-result'>");
  656. parts.push(opts.formatResult(this));
  657. parts.push("</li>");
  658. });
  659. if (data.more === true) {
  660. parts.push("<li class='select2-more-results'>Loading more results...</li>");
  661. }
  662. render(parts.join(""));
  663. results.children(".select2-result").each(function (i) {
  664. var d = data.results[i];
  665. $(this).data("select2-data", d);
  666. });
  667. this.postprocessResults(data, initial);
  668. })});
  669. },
  670. cancel: function () {
  671. this.close();
  672. },
  673. blur: function () {
  674. /* we do this in a timeout so that current event processing can complete before this code is executed.
  675. this allows tab index to be preserved even if this code blurs the textfield */
  676. window.setTimeout(this.bind(function () {
  677. this.close();
  678. this.container.removeClass("select2-container-active");
  679. this.clearSearch();
  680. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  681. this.search.blur();
  682. }), 10);
  683. },
  684. focusSearch: function () {
  685. /* we do this in a timeout so that current event processing can complete before this code is executed.
  686. this makes sure the search field is focussed even if the current event would blur it */
  687. window.setTimeout(this.bind(function () {
  688. this.search.focus();
  689. }), 10);
  690. },
  691. selectHighlighted: function () {
  692. var data = this.results.find(".select2-highlighted:not(.select2-disabled)").data("select2-data");
  693. if (data) {
  694. this.onSelect(data);
  695. }
  696. },
  697. getPlaceholder: function () {
  698. return this.opts.element.attr("placeholder") || this.opts.element.data("placeholder") || this.opts.placeholder;
  699. },
  700. /**
  701. * Get the desired width for the container element. This is
  702. * derived first from option `width` passed to select2, then
  703. * the inline 'style' on the original element, and finally
  704. * falls back to the jQuery calculated element width.
  705. *
  706. * @returns The width string (with units) for the container.
  707. */
  708. getContainerWidth: function () {
  709. var style, attrs, matches, i, l;
  710. if (this.opts.width !== undefined)
  711. return this.opts.width;
  712. style = this.opts.element.attr('style');
  713. if (style !== undefined) {
  714. attrs = style.split(';');
  715. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  716. matches = attrs[i].replace(/\s/g, '')
  717. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  718. if (matches !== null && matches.length >= 1)
  719. return matches[1];
  720. }
  721. }
  722. return this.opts.element.width() + 'px';
  723. }
  724. });
  725. SingleSelect2 = clazz(AbstractSelect2, {
  726. createContainer: function () {
  727. return $("<div></div>", {
  728. "class": "select2-container",
  729. "style": "width: " + this.getContainerWidth()
  730. }).html([
  731. " <a href='javascript:void(0)' class='select2-choice'>",
  732. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  733. " <div><b></b></div>" ,
  734. "</a>",
  735. " <div class='select2-drop' style='display:none;'>" ,
  736. " <div class='select2-search'>" ,
  737. " <input type='text' autocomplete='off'/>" ,
  738. " </div>" ,
  739. " <ul class='select2-results'>" ,
  740. " </ul>" ,
  741. "</div>"].join(""));
  742. },
  743. open: function () {
  744. if (this.opened()) return;
  745. this.parent.open.apply(this, arguments);
  746. },
  747. close: function () {
  748. if (!this.opened()) return;
  749. this.parent.close.apply(this, arguments);
  750. },
  751. focus: function () {
  752. this.close();
  753. this.selection.focus();
  754. },
  755. isFocused: function () {
  756. return this.selection.is(":focus");
  757. },
  758. cancel: function () {
  759. this.parent.cancel.apply(this, arguments);
  760. this.selection.focus();
  761. },
  762. initContainer: function () {
  763. var selection, container = this.container, clickingInside = false,
  764. selector = ".select2-choice";
  765. this.selection = selection = container.find(selector);
  766. this.search.bind("keydown", this.bind(function (e) {
  767. switch (e.which) {
  768. case KEY.UP:
  769. case KEY.DOWN:
  770. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  771. killEvent(e);
  772. return;
  773. case KEY.TAB:
  774. case KEY.ENTER:
  775. this.selectHighlighted();
  776. killEvent(e);
  777. return;
  778. case KEY.ESC:
  779. this.cancel(e);
  780. e.preventDefault();
  781. return;
  782. }
  783. }));
  784. container.delegate(selector, "click", this.bind(function (e) {
  785. clickingInside = true;
  786. if (this.opened()) {
  787. this.close();
  788. selection.focus();
  789. } else if (this.enabled) {
  790. this.open();
  791. }
  792. e.preventDefault();
  793. clickingInside = false;
  794. }));
  795. container.delegate(selector, "keydown", this.bind(function (e) {
  796. if (!this.enabled || e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  797. return;
  798. }
  799. this.open();
  800. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN || e.which === KEY.SPACE) {
  801. // prevent the page from scrolling
  802. killEvent(e);
  803. }
  804. if (e.which === KEY.ENTER) {
  805. // do not propagate the event otherwise we open, and propagate enter which closes
  806. killEvent(e);
  807. }
  808. }));
  809. container.delegate(selector, "focus", function () { if (this.enabled) container.addClass("select2-container-active"); });
  810. container.delegate(selector, "blur", this.bind(function () {
  811. if (clickingInside) return;
  812. if (!this.opened()) this.blur();
  813. }));
  814. selection.delegate("abbr", "click", this.bind(function (e) {
  815. if (!this.enabled) return;
  816. this.val("");
  817. killEvent(e);
  818. this.close();
  819. this.triggerChange();
  820. }));
  821. this.setPlaceholder();
  822. },
  823. /**
  824. * Sets selection based on source element's value
  825. */
  826. initSelection: function () {
  827. var selected;
  828. if (this.opts.element.val() === "") {
  829. this.updateSelection({id: "", text: ""});
  830. } else {
  831. selected = this.opts.initSelection.call(null, this.opts.element);
  832. if (selected !== undefined && selected !== null) {
  833. this.updateSelection(selected);
  834. }
  835. }
  836. this.close();
  837. this.setPlaceholder();
  838. },
  839. prepareOpts: function () {
  840. var opts = this.parent.prepareOpts.apply(this, arguments);
  841. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  842. // install sthe selection initializer
  843. opts.initSelection = function (element) {
  844. var selected = element.find(":selected");
  845. // a single select box always has a value, no need to null check 'selected'
  846. return {id: selected.attr("value"), text: selected.text()};
  847. };
  848. }
  849. return opts;
  850. },
  851. setPlaceholder: function () {
  852. var placeholder = this.getPlaceholder();
  853. if (this.opts.element.val() === "" && placeholder !== undefined) {
  854. // check for a first blank option if attached to a select
  855. if (this.select && this.select.find("option:first").text() !== "") return;
  856. if (typeof(placeholder) === "object") {
  857. this.updateSelection(placeholder);
  858. } else {
  859. this.selection.find("span").html(placeholder);
  860. }
  861. this.selection.addClass("select2-default");
  862. this.selection.find("abbr").hide();
  863. }
  864. },
  865. postprocessResults: function (data, initial) {
  866. var selected = 0, self = this, showSearchInput = true;
  867. // find the selected element in the result list
  868. this.results.find(".select2-result").each(function (i) {
  869. if (equal(self.id($(this).data("select2-data")), self.opts.element.val())) {
  870. selected = i;
  871. return false;
  872. }
  873. });
  874. // and highlight it
  875. this.highlight(selected);
  876. // hide the search box if this is the first we got the results and there are a few of them
  877. if (initial === true) {
  878. showSearchInput = this.showSearchInput = data.results.length >= this.opts.minimumResultsForSearch;
  879. this.container.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  880. //add "select2-with-searchbox" to the container if search box is shown
  881. this.container[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  882. }
  883. },
  884. onSelect: function (data) {
  885. var old = this.opts.element.val();
  886. this.opts.element.val(this.id(data));
  887. this.updateSelection(data);
  888. this.close();
  889. this.selection.focus();
  890. if (!equal(old, this.id(data))) { this.triggerChange(); }
  891. },
  892. updateSelection: function (data) {
  893. this.selection
  894. .find("span")
  895. .html(this.opts.formatSelection(data));
  896. this.selection.removeClass("select2-default");
  897. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  898. this.selection.find("abbr").show();
  899. }
  900. },
  901. val: function () {
  902. var val, data = null;
  903. if (arguments.length === 0) {
  904. return this.opts.element.val();
  905. }
  906. val = arguments[0];
  907. if (this.select) {
  908. // val is an id
  909. this.select
  910. .val(val)
  911. .find(":selected").each(function () {
  912. data = {id: $(this).attr("value"), text: $(this).text()};
  913. return false;
  914. });
  915. this.updateSelection(data);
  916. } else {
  917. // val is an object. !val is true for [undefined,null,'']
  918. this.opts.element.val(!val ? "" : this.id(val));
  919. this.updateSelection(val);
  920. }
  921. this.setPlaceholder();
  922. },
  923. clearSearch: function () {
  924. this.search.val("");
  925. }
  926. });
  927. MultiSelect2 = clazz(AbstractSelect2, {
  928. createContainer: function () {
  929. return $("<div></div>", {
  930. "class": "select2-container select2-container-multi",
  931. "style": "width: " + this.getContainerWidth()
  932. }).html([
  933. " <ul class='select2-choices'>",
  934. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  935. " <li class='select2-search-field'>" ,
  936. " <input type='text' autocomplete='off' style='width: 25px;'>" ,
  937. " </li>" ,
  938. "</ul>" ,
  939. "<div class='select2-drop' style='display:none;'>" ,
  940. " <ul class='select2-results'>" ,
  941. " </ul>" ,
  942. "</div>"].join(""));
  943. },
  944. prepareOpts: function () {
  945. var opts = this.parent.prepareOpts.apply(this, arguments);
  946. opts = $.extend({}, {
  947. closeOnSelect: true
  948. }, opts);
  949. // TODO validate placeholder is a string if specified
  950. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  951. // install sthe selection initializer
  952. opts.initSelection = function (element) {
  953. var data = [];
  954. element.find(":selected").each(function () {
  955. data.push({id: $(this).attr("value"), text: $(this).text()});
  956. });
  957. return data;
  958. };
  959. }
  960. return opts;
  961. },
  962. initContainer: function () {
  963. var selector = ".select2-choices", selection;
  964. this.searchContainer = this.container.find(".select2-search-field");
  965. this.selection = selection = this.container.find(selector);
  966. this.search.bind("keydown", this.bind(function (e) {
  967. if (!this.enabled) return;
  968. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  969. this.close();
  970. var choices,
  971. selected = selection.find(".select2-search-choice-focus");
  972. if (selected.length > 0) {
  973. this.unselect(selected.first());
  974. this.search.width(10);
  975. killEvent(e);
  976. return;
  977. }
  978. choices = selection.find(".select2-search-choice");
  979. if (choices.length > 0) {
  980. choices.last().addClass("select2-search-choice-focus");
  981. }
  982. } else {
  983. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  984. }
  985. if (this.opened()) {
  986. switch (e.which) {
  987. case KEY.UP:
  988. case KEY.DOWN:
  989. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  990. killEvent(e);
  991. return;
  992. case KEY.ENTER:
  993. case KEY.TAB:
  994. this.selectHighlighted();
  995. killEvent(e);
  996. return;
  997. case KEY.ESC:
  998. this.cancel(e);
  999. e.preventDefault();
  1000. return;
  1001. }
  1002. }
  1003. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1004. return;
  1005. }
  1006. this.open();
  1007. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1008. // prevent the page from scrolling
  1009. killEvent(e);
  1010. }
  1011. }));
  1012. this.search.bind("keyup", this.bind(this.resizeSearch));
  1013. this.container.delegate(selector, "click", this.bind(function (e) {
  1014. if (!this.enabled) return;
  1015. this.open();
  1016. this.focusSearch();
  1017. e.preventDefault();
  1018. }));
  1019. this.container.delegate(selector, "focus", this.bind(function () {
  1020. if (!this.enabled) return;
  1021. this.container.addClass("select2-container-active");
  1022. this.clearPlaceholder();
  1023. }));
  1024. // set the placeholder if necessary
  1025. this.clearSearch();
  1026. },
  1027. enable: function() {
  1028. if (this.enabled) return;
  1029. this.parent.enable.apply(this, arguments);
  1030. this.search.show();
  1031. },
  1032. disable: function() {
  1033. if (!this.enabled) return;
  1034. this.parent.disable.apply(this, arguments);
  1035. this.search.hide();
  1036. },
  1037. initSelection: function () {
  1038. var data;
  1039. if (this.opts.element.val() === "") {
  1040. this.updateSelection([]);
  1041. }
  1042. if (this.select || this.opts.element.val() !== "") {
  1043. data = this.opts.initSelection.call(null, this.opts.element);
  1044. if (data !== undefined && data !== null) {
  1045. this.updateSelection(data);
  1046. }
  1047. }
  1048. this.close();
  1049. // set the placeholder if necessary
  1050. this.clearSearch();
  1051. },
  1052. clearSearch: function () {
  1053. var placeholder = this.getPlaceholder();
  1054. if (placeholder !== undefined
  1055. && this.getVal().length === 0
  1056. && this.search.hasClass("select2-focused") === false) {
  1057. this.search.val(placeholder).addClass("select2-default");
  1058. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1059. this.search.width(this.getContainerWidth());
  1060. } else {
  1061. this.search.val("").width(10);
  1062. }
  1063. },
  1064. clearPlaceholder: function () {
  1065. if (this.search.hasClass("select2-default")) {
  1066. this.search.val("").removeClass("select2-default");
  1067. }
  1068. },
  1069. open: function () {
  1070. if (this.opened()) return;
  1071. this.parent.open.apply(this, arguments);
  1072. this.resizeSearch();
  1073. this.focusSearch();
  1074. },
  1075. close: function () {
  1076. if (!this.opened()) return;
  1077. this.parent.close.apply(this, arguments);
  1078. },
  1079. focus: function () {
  1080. this.close();
  1081. this.search.focus();
  1082. },
  1083. isFocused: function () {
  1084. return this.search.hasClass("select2-focused");
  1085. },
  1086. updateSelection: function (data) {
  1087. var ids = [], filtered = [], self = this;
  1088. // filter out duplicates
  1089. $(data).each(function () {
  1090. if (indexOf(self.id(this), ids) < 0) {
  1091. ids.push(self.id(this));
  1092. filtered.push(this);
  1093. }
  1094. });
  1095. data = filtered;
  1096. this.selection.find(".select2-search-choice").remove();
  1097. $(data).each(function () {
  1098. self.addSelectedChoice(this);
  1099. });
  1100. self.postprocessResults();
  1101. },
  1102. onSelect: function (data) {
  1103. this.addSelectedChoice(data);
  1104. if (this.select) { this.postprocessResults(); }
  1105. if (this.opts.closeOnSelect) {
  1106. this.close();
  1107. this.search.width(10);
  1108. } else {
  1109. this.search.width(10);
  1110. this.resizeSearch();
  1111. }
  1112. // since its not possible to select an element that has already been
  1113. // added we do not need to check if this is a new element before firing change
  1114. this.triggerChange();
  1115. this.focusSearch();
  1116. },
  1117. cancel: function () {
  1118. this.close();
  1119. this.focusSearch();
  1120. },
  1121. addSelectedChoice: function (data) {
  1122. var choice,
  1123. id = this.id(data),
  1124. parts,
  1125. val = this.getVal();
  1126. parts = ["<li class='select2-search-choice'>",
  1127. this.opts.formatSelection(data),
  1128. "<a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>",
  1129. "</li>"
  1130. ];
  1131. choice = $(parts.join(""));
  1132. choice.find("a")
  1133. .bind("click dblclick", this.bind(function (e) {
  1134. if (!this.enabled) return;
  1135. this.unselect($(e.target));
  1136. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1137. killEvent(e);
  1138. this.close();
  1139. this.focusSearch();
  1140. })).bind("focus", this.bind(function () {
  1141. if (!this.enabled) return;
  1142. this.container.addClass("select2-container-active");
  1143. }));
  1144. choice.data("select2-data", data);
  1145. choice.insertBefore(this.searchContainer);
  1146. val.push(id);
  1147. this.setVal(val);
  1148. },
  1149. unselect: function (selected) {
  1150. var val = this.getVal(),
  1151. index;
  1152. selected = selected.closest(".select2-search-choice");
  1153. if (selected.length === 0) {
  1154. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1155. }
  1156. index = indexOf(this.id(selected.data("select2-data")), val);
  1157. if (index >= 0) {
  1158. val.splice(index, 1);
  1159. this.setVal(val);
  1160. if (this.select) this.postprocessResults();
  1161. }
  1162. selected.remove();
  1163. this.triggerChange();
  1164. },
  1165. postprocessResults: function () {
  1166. var val = this.getVal(),
  1167. choices = this.results.find(".select2-result"),
  1168. self = this;
  1169. choices.each(function () {
  1170. var choice = $(this), id = self.id(choice.data("select2-data"));
  1171. if (indexOf(id, val) >= 0) {
  1172. choice.addClass("select2-disabled");
  1173. } else {
  1174. choice.removeClass("select2-disabled");
  1175. }
  1176. });
  1177. choices.each(function (i) {
  1178. if (!$(this).hasClass("select2-disabled")) {
  1179. self.highlight(i);
  1180. return false;
  1181. }
  1182. });
  1183. },
  1184. resizeSearch: function () {
  1185. var minimumWidth, left, maxWidth, containerLeft, searchWidth;
  1186. minimumWidth = measureTextWidth(this.search) + 10;
  1187. left = this.search.offset().left;
  1188. maxWidth = this.selection.width();
  1189. containerLeft = this.selection.offset().left;
  1190. searchWidth = maxWidth - (left - containerLeft) - getSideBorderPadding(this.search);
  1191. if (searchWidth < minimumWidth) {
  1192. searchWidth = maxWidth - getSideBorderPadding(this.search);
  1193. }
  1194. if (searchWidth < 40) {
  1195. searchWidth = maxWidth - getSideBorderPadding(this.search);
  1196. }
  1197. this.search.width(searchWidth);
  1198. },
  1199. getVal: function () {
  1200. var val;
  1201. if (this.select) {
  1202. val = this.select.val();
  1203. return val === null ? [] : val;
  1204. } else {
  1205. val = this.opts.element.val();
  1206. return splitVal(val, ",");
  1207. }
  1208. },
  1209. setVal: function (val) {
  1210. var unique;
  1211. if (this.select) {
  1212. this.select.val(val);
  1213. } else {
  1214. unique = [];
  1215. // filter out duplicates
  1216. $(val).each(function () {
  1217. if (indexOf(this, unique) < 0) unique.push(this);
  1218. });
  1219. this.opts.element.val(unique.length === 0 ? "" : unique.join(","));
  1220. }
  1221. },
  1222. val: function () {
  1223. var val, data = [], self=this;
  1224. if (arguments.length === 0) {
  1225. return this.getVal();
  1226. }
  1227. val = arguments[0];
  1228. if (this.select) {
  1229. // val is a list of ids
  1230. this.setVal(val);
  1231. this.select.find(":selected").each(function () {
  1232. data.push({id: $(this).attr("value"), text: $(this).text()});
  1233. });
  1234. this.updateSelection(data);
  1235. } else {
  1236. val = (val === null) ? [] : val;
  1237. this.setVal(val);
  1238. // val is a list of objects
  1239. $(val).each(function () { data.push(self.id(this)); });
  1240. this.setVal(data);
  1241. this.updateSelection(val);
  1242. }
  1243. this.clearSearch();
  1244. },
  1245. onSortStart: function() {
  1246. if (this.select) {
  1247. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  1248. }
  1249. // collapse search field into 0 width so its container can be collapsed as well
  1250. this.search.width(0);
  1251. // hide the container
  1252. this.searchContainer.hide();
  1253. },
  1254. onSortEnd:function() {
  1255. var val=[], self=this;
  1256. // show search and move it to the end of the list
  1257. this.searchContainer.show();
  1258. // make sure the search container is the last item in the list
  1259. this.searchContainer.appendTo(this.searchContainer.parent());
  1260. // since we collapsed the width in dragStarteed, we resize it here
  1261. this.resizeSearch();
  1262. // update selection
  1263. this.selection.find(".select2-search-choice").each(function() {
  1264. val.push(self.opts.id($(this).data("select2-data")));
  1265. });
  1266. this.setVal(val);
  1267. this.triggerChange();
  1268. }
  1269. });
  1270. $.fn.select2 = function () {
  1271. var args = Array.prototype.slice.call(arguments, 0),
  1272. opts,
  1273. select2,
  1274. value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable"];
  1275. this.each(function () {
  1276. if (args.length === 0 || typeof(args[0]) === "object") {
  1277. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1278. opts.element = $(this);
  1279. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1280. multiple = opts.element.attr("multiple");
  1281. } else {
  1282. multiple = opts.multiple || false;
  1283. if ("tags" in opts) {opts.multiple = multiple = true;}
  1284. }
  1285. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1286. select2.init(opts);
  1287. } else if (typeof(args[0]) === "string") {
  1288. if (indexOf(args[0], allowedMethods) < 0) {
  1289. throw "Unknown method: " + args[0];
  1290. }
  1291. value = undefined;
  1292. select2 = $(this).data("select2");
  1293. if (select2 === undefined) return;
  1294. if (args[0] === "container") {
  1295. value=select2.container;
  1296. } else {
  1297. value = select2[args[0]].apply(select2, args.slice(1));
  1298. }
  1299. if (value !== undefined) {return false;}
  1300. } else {
  1301. throw "Invalid arguments to select2 plugin: " + args;
  1302. }
  1303. });
  1304. return (value === undefined) ? this : value;
  1305. };
  1306. // exports
  1307. window.Select2 = {
  1308. query: {
  1309. ajax: ajax,
  1310. local: local,
  1311. tags: tags
  1312. }, util: {
  1313. debounce: debounce
  1314. }, "class": {
  1315. "abstract": AbstractSelect2,
  1316. "single": SingleSelect2,
  1317. "multi": MultiSelect2
  1318. }
  1319. };
  1320. }(jQuery));