select2.js 61 KB

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