select2.js 60 KB

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