select2.js 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254
  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. if (k.metaKey) return true;
  75. return false;
  76. },
  77. isFunctionKey: function (k) {
  78. k = k.which ? k.which : k;
  79. return k >= 112 && k <= 123;
  80. }
  81. };
  82. nextUid=(function() { var counter=1; return function() { return counter++; }; }());
  83. function escapeMarkup(markup) {
  84. if (markup && typeof(markup) === "string") {
  85. return markup.replace(/&/g, "&amp;");
  86. } else {
  87. return markup;
  88. }
  89. }
  90. function indexOf(value, array) {
  91. var i = 0, l = array.length, v;
  92. if (typeof value === "undefined") {
  93. return -1;
  94. }
  95. if (value.constructor === String) {
  96. for (; i < l; i = i + 1) if (value.localeCompare(array[i]) === 0) return i;
  97. } else {
  98. for (; i < l; i = i + 1) {
  99. v = array[i];
  100. if (v.constructor === String) {
  101. if (v.localeCompare(value) === 0) return i;
  102. } else {
  103. if (v === value) return i;
  104. }
  105. }
  106. }
  107. return -1;
  108. }
  109. /**
  110. * Compares equality of a and b taking into account that a and b may be strings, in which case localeCompare is used
  111. * @param a
  112. * @param b
  113. */
  114. function equal(a, b) {
  115. if (a === b) return true;
  116. if (a === undefined || b === undefined) return false;
  117. if (a === null || b === null) return false;
  118. if (a.constructor === String) return a.localeCompare(b) === 0;
  119. if (b.constructor === String) return b.localeCompare(a) === 0;
  120. return false;
  121. }
  122. /**
  123. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  124. * strings
  125. * @param string
  126. * @param separator
  127. */
  128. function splitVal(string, separator) {
  129. var val, i, l;
  130. if (string === null || string.length < 1) return [];
  131. val = string.split(separator);
  132. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  133. return val;
  134. }
  135. function getSideBorderPadding(element) {
  136. return element.outerWidth() - element.width();
  137. }
  138. function installKeyUpChangeEvent(element) {
  139. var key="keyup-change-value";
  140. element.bind("keydown", function () {
  141. if ($.data(element, key) === undefined) {
  142. $.data(element, key, element.val());
  143. }
  144. });
  145. element.bind("keyup", function () {
  146. var val= $.data(element, key);
  147. if (val !== undefined && element.val() !== val) {
  148. $.removeData(element, key);
  149. element.trigger("keyup-change");
  150. }
  151. });
  152. }
  153. $(document).delegate("*", "mousemove", function (e) {
  154. $.data(document, "select2-lastpos", {x: e.pageX, y: e.pageY});
  155. });
  156. /**
  157. * filters mouse events so an event is fired only if the mouse moved.
  158. *
  159. * filters out mouse events that occur when mouse is stationary but
  160. * the elements under the pointer are scrolled.
  161. */
  162. function installFilteredMouseMove(element) {
  163. element.bind("mousemove", function (e) {
  164. var lastpos = $.data(document, "select2-lastpos");
  165. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  166. $(e.target).trigger("mousemove-filtered", e);
  167. }
  168. });
  169. }
  170. /**
  171. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  172. * within the last quietMillis milliseconds.
  173. *
  174. * @param quietMillis number of milliseconds to wait before invoking fn
  175. * @param fn function to be debounced
  176. * @return debounced version of fn
  177. */
  178. function debounce(quietMillis, fn) {
  179. var timeout;
  180. return function () {
  181. window.clearTimeout(timeout);
  182. timeout = window.setTimeout(fn, quietMillis);
  183. };
  184. }
  185. /**
  186. * A simple implementation of a thunk
  187. * @param formula function used to lazily initialize the thunk
  188. * @return {Function}
  189. */
  190. function thunk(formula) {
  191. var evaluated = false,
  192. value;
  193. return function() {
  194. if (evaluated === false) { value = formula(); evaluated = true; }
  195. return value;
  196. };
  197. };
  198. function installDebouncedScroll(threshold, element) {
  199. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  200. element.bind("scroll", function (e) {
  201. if (indexOf(e.target, element.get()) >= 0) notify(e);
  202. });
  203. }
  204. function killEvent(event) {
  205. event.preventDefault();
  206. event.stopPropagation();
  207. }
  208. function measureTextWidth(e) {
  209. if (!sizer){
  210. var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
  211. sizer = $("<div></div>").css({
  212. position: "absolute",
  213. left: "-10000px",
  214. top: "-10000px",
  215. display: "none",
  216. fontSize: style.fontSize,
  217. fontFamily: style.fontFamily,
  218. fontStyle: style.fontStyle,
  219. fontWeight: style.fontWeight,
  220. letterSpacing: style.letterSpacing,
  221. textTransform: style.textTransform,
  222. whiteSpace: "nowrap"
  223. });
  224. $("body").append(sizer);
  225. }
  226. sizer.text(e.val());
  227. return sizer.width();
  228. }
  229. function markMatch(text, term, markup) {
  230. var match=text.toUpperCase().indexOf(term.toUpperCase()),
  231. tl=term.length;
  232. if (match<0) {
  233. markup.push(text);
  234. return;
  235. }
  236. markup.push(text.substring(0, match));
  237. markup.push("<span class='select2-match'>");
  238. markup.push(text.substring(match, match + tl));
  239. markup.push("</span>");
  240. markup.push(text.substring(match + tl, text.length));
  241. }
  242. /**
  243. * Produces an ajax-based query function
  244. *
  245. * @param options object containing configuration paramters
  246. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  247. * @param options.url url for the data
  248. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  249. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
  250. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  251. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  252. * The expected format is an object containing the following keys:
  253. * results array of objects that will be used as choices
  254. * more (optional) boolean indicating whether there are more results available
  255. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  256. */
  257. function ajax(options) {
  258. var timeout, // current scheduled but not yet executed request
  259. requestSequence = 0, // sequence used to drop out-of-order responses
  260. handler = null,
  261. quietMillis = options.quietMillis || 100;
  262. return function (query) {
  263. window.clearTimeout(timeout);
  264. timeout = window.setTimeout(function () {
  265. requestSequence += 1; // increment the sequence
  266. var requestNumber = requestSequence, // this request's sequence number
  267. data = options.data, // ajax data function
  268. transport = options.transport || $.ajax,
  269. type = options.type || 'GET'; // set type of request (GET or POST)
  270. data = data.call(this, query.term, query.page, query.context);
  271. if( null !== handler) { handler.abort(); }
  272. handler = transport.call(null, {
  273. url: options.url,
  274. dataType: options.dataType,
  275. data: data,
  276. type: type,
  277. success: function (data) {
  278. if (requestNumber < requestSequence) {
  279. return;
  280. }
  281. // TODO 3.0 - replace query.page with query so users have access to term, page, etc.
  282. var results = options.results(data, query.page);
  283. query.callback(results);
  284. }
  285. });
  286. }, quietMillis);
  287. };
  288. }
  289. /**
  290. * Produces a query function that works with a local array
  291. *
  292. * @param options object containing configuration parameters. The options parameter can either be an array or an
  293. * object.
  294. *
  295. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  296. *
  297. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  298. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  299. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  300. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  301. * the text.
  302. */
  303. function local(options) {
  304. var data = options, // data elements
  305. dataText,
  306. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  307. if (!$.isArray(data)) {
  308. text = data.text;
  309. // if text is not a function we assume it to be a key name
  310. if (!$.isFunction(text)) {
  311. 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
  312. text = function (item) { return item[dataText]; };
  313. }
  314. data = data.results;
  315. }
  316. return function (query) {
  317. var t = query.term, filtered = {};
  318. if (t === "") {
  319. query.callback({results: data});
  320. return;
  321. }
  322. filtered.results = $(data)
  323. .filter(function () {return query.matcher(t, text(this));})
  324. .get();
  325. query.callback(filtered);
  326. };
  327. }
  328. // TODO javadoc
  329. function tags(data) {
  330. // TODO even for a function we should probably return a wrapper that does the same object/string check as
  331. // the function for arrays. otherwise only functions that return objects are supported.
  332. if ($.isFunction(data)) {
  333. return data;
  334. }
  335. // if not a function we assume it to be an array
  336. return function (query) {
  337. var t = query.term, filtered = {results: []};
  338. $(data).each(function () {
  339. var isObject = this.text !== undefined,
  340. text = isObject ? this.text : this;
  341. if (t === "" || query.matcher(t, text)) {
  342. filtered.results.push(isObject ? this : {id: this, text: this});
  343. }
  344. });
  345. query.callback(filtered);
  346. };
  347. }
  348. /**
  349. * Checks if the formatter function should be used.
  350. *
  351. * Throws an error if it is not a function. Returns true if it should be used,
  352. * false if no formatting should be performed.
  353. *
  354. * @param formatter
  355. */
  356. function checkFormatter(formatter, formatterName) {
  357. if ($.isFunction(formatter)) return true;
  358. if (!formatter) return fasle;
  359. throw new Error("formatterName must be a function or a falsy value");
  360. }
  361. function evaluate(val) {
  362. return $.isFunction(val) ? val() : val;
  363. }
  364. function countResults(results) {
  365. var count = 0;
  366. $.each(results, function(i, item) {
  367. if (item.children) {
  368. count += countResults(item.children);
  369. } else {
  370. count++;
  371. }
  372. });
  373. return count;
  374. }
  375. /**
  376. * blurs any Select2 container that has focus when an element outside them was clicked or received focus
  377. *
  378. * also takes care of clicks on label tags that point to the source element
  379. */
  380. $(document).ready(function () {
  381. $(document).delegate("*", "mousedown touchend", function (e) {
  382. var target = $(e.target).closest("div.select2-container").get(0), attr;
  383. if (target) {
  384. $(document).find("div.select2-container-active").each(function () {
  385. if (this !== target) $(this).data("select2").blur();
  386. });
  387. } else {
  388. target = $(e.target).closest("div.select2-drop").get(0);
  389. $(document).find("div.select2-drop-active").each(function () {
  390. if (this !== target) $(this).data("select2").blur();
  391. });
  392. }
  393. target=$(e.target);
  394. attr = target.attr("for");
  395. if ("LABEL" === e.target.tagName && attr && attr.length > 0) {
  396. target = $("#"+attr);
  397. target = target.data("select2");
  398. if (target !== undefined) { target.focus(); e.preventDefault();}
  399. }
  400. });
  401. });
  402. /**
  403. * Creates a new class
  404. *
  405. * @param superClass
  406. * @param methods
  407. */
  408. function clazz(SuperClass, methods) {
  409. var constructor = function () {};
  410. constructor.prototype = new SuperClass;
  411. constructor.prototype.constructor = constructor;
  412. constructor.prototype.parent = SuperClass.prototype;
  413. constructor.prototype = $.extend(constructor.prototype, methods);
  414. return constructor;
  415. }
  416. AbstractSelect2 = clazz(Object, {
  417. // abstract
  418. bind: function (func) {
  419. var self = this;
  420. return function () {
  421. func.apply(self, arguments);
  422. };
  423. },
  424. // abstract
  425. init: function (opts) {
  426. var results, search, resultsSelector = ".select2-results";
  427. // prepare options
  428. this.opts = opts = this.prepareOpts(opts);
  429. this.id=opts.id;
  430. // destroy if called on an existing component
  431. if (opts.element.data("select2") !== undefined &&
  432. opts.element.data("select2") !== null) {
  433. this.destroy();
  434. }
  435. this.enabled=true;
  436. this.container = this.createContainer();
  437. this.containerId="s2id"+nextUid();
  438. this.container.attr("id", this.containerId);
  439. // cache the body so future lookups are cheap
  440. this.body = thunk(function() { return opts.element.closest("body"); });
  441. if (opts.element.attr("class") !== undefined) {
  442. this.container.addClass(opts.element.attr("class"));
  443. }
  444. this.container.css(evaluate(opts.containerCss));
  445. this.container.addClass(evaluate(opts.containerCssClass));
  446. // swap container for the element
  447. this.opts.element
  448. .data("select2", this)
  449. .hide()
  450. .before(this.container);
  451. this.container.data("select2", this);
  452. this.dropdown = this.container.find(".select2-drop");
  453. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  454. this.dropdown.data("select2", this);
  455. this.results = results = this.container.find(resultsSelector);
  456. this.search = search = this.container.find("input.select2-input");
  457. search.attr("tabIndex", this.opts.element.attr("tabIndex"));
  458. this.resultsPage = 0;
  459. this.context = null;
  460. // initialize the container
  461. this.initContainer();
  462. this.initContainerWidth();
  463. installFilteredMouseMove(this.results);
  464. this.dropdown.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
  465. installDebouncedScroll(80, this.results);
  466. this.dropdown.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  467. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  468. if ($.fn.mousewheel) {
  469. results.mousewheel(function (e, delta, deltaX, deltaY) {
  470. var top = results.scrollTop(), height;
  471. if (deltaY > 0 && top - deltaY <= 0) {
  472. results.scrollTop(0);
  473. killEvent(e);
  474. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  475. results.scrollTop(results.get(0).scrollHeight - results.height());
  476. killEvent(e);
  477. }
  478. });
  479. }
  480. installKeyUpChangeEvent(search);
  481. search.bind("keyup-change", this.bind(this.updateResults));
  482. search.bind("focus", function () { search.addClass("select2-focused"); if (search.val() === " ") search.val(""); });
  483. search.bind("blur", function () { search.removeClass("select2-focused");});
  484. this.dropdown.delegate(resultsSelector, "mouseup", this.bind(function (e) {
  485. if ($(e.target).closest(".select2-result-selectable:not(.select2-disabled)").length > 0) {
  486. this.highlightUnderEvent(e);
  487. this.selectHighlighted(e);
  488. } else {
  489. this.focusSearch();
  490. }
  491. killEvent(e);
  492. }));
  493. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  494. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  495. // dom it will trigger the popup close, which is not what we want
  496. this.dropdown.bind("click mouseup mousedown", function (e) { e.stopPropagation(); });
  497. if ($.isFunction(this.opts.initSelection)) {
  498. // initialize selection based on the current value of the source element
  499. this.initSelection();
  500. // if the user has provided a function that can set selection based on the value of the source element
  501. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  502. this.monitorSource();
  503. }
  504. if (opts.element.is(":disabled") || opts.element.is("[readonly='readonly']")) this.disable();
  505. },
  506. // abstract
  507. destroy: function () {
  508. var select2 = this.opts.element.data("select2");
  509. if (select2 !== undefined) {
  510. select2.container.remove();
  511. select2.dropdown.remove();
  512. select2.opts.element
  513. .removeData("select2")
  514. .unbind(".select2")
  515. .show();
  516. }
  517. },
  518. // abstract
  519. prepareOpts: function (opts) {
  520. var element, select, idKey, ajaxUrl;
  521. element = opts.element;
  522. if (element.get(0).tagName.toLowerCase() === "select") {
  523. this.select = select = opts.element;
  524. }
  525. //Custom tags separator.
  526. opts.separator = opts.separator || ",";
  527. if (select) {
  528. // these options are not allowed when attached to a select because they are picked up off the element itself
  529. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  530. if (this in opts) {
  531. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  532. }
  533. });
  534. }
  535. opts = $.extend({}, {
  536. populateResults: function(container, results, query) {
  537. var populate, data, result, children, id=this.opts.id, self=this;
  538. populate=function(results, container, depth) {
  539. var i, l, result, selectable, compound, node, label, innerContainer, formatted;
  540. for (i = 0, l = results.length; i < l; i = i + 1) {
  541. result=results[i];
  542. selectable=id(result) !== undefined;
  543. compound=("children" in result) && result.children.length > 0;
  544. node=$("<li></li>");
  545. node.addClass("select2-results-dept-"+depth);
  546. node.addClass("select2-result");
  547. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  548. if (compound) { node.addClass("select2-result-with-children"); }
  549. node.addClass(self.opts.formatResultCssClass(result));
  550. label=$("<div></div>");
  551. label.addClass("select2-result-label");
  552. formatted=opts.formatResult(result, label, query);
  553. if (formatted!==undefined) {
  554. label.html(escapeMarkup(formatted));
  555. }
  556. node.append(label);
  557. if (compound) {
  558. innerContainer=$("<ul></ul>");
  559. innerContainer.addClass("select2-result-sub");
  560. populate(result.children, innerContainer, depth+1);
  561. node.append(innerContainer);
  562. }
  563. node.data("select2-data", result);
  564. container.append(node);
  565. }
  566. };
  567. populate(results, container, 0);
  568. }
  569. }, $.fn.select2.defaults, opts);
  570. if (typeof(opts.id) !== "function") {
  571. idKey = opts.id;
  572. opts.id = function (e) { return e[idKey]; };
  573. }
  574. if (select) {
  575. opts.query = this.bind(function (query) {
  576. var data = { results: [], more: false },
  577. term = query.term,
  578. children, firstChild, process;
  579. process=function(element, collection) {
  580. var group;
  581. if (element.is("option")) {
  582. if (query.matcher(term, element.text(), element)) {
  583. collection.push({id:element.attr("value"), text:element.text(), element: element.get(), css: element.attr("class")});
  584. }
  585. } else if (element.is("optgroup")) {
  586. group={text:element.attr("label"), children:[], element: element.get(), css: element.attr("class")};
  587. element.children().each2(function(i, elm) { process(elm, group.children); });
  588. if (group.children.length>0) {
  589. collection.push(group);
  590. }
  591. }
  592. };
  593. children=element.children();
  594. // ignore the placeholder option if there is one
  595. if (this.getPlaceholder() !== undefined && children.length > 0) {
  596. firstChild = children[0];
  597. if ($(firstChild).text() === "") {
  598. children=children.not(firstChild);
  599. }
  600. }
  601. children.each2(function(i, elm) { process(elm, data.results); });
  602. query.callback(data);
  603. });
  604. // this is needed because inside val() we construct choices from options and there id is hardcoded
  605. opts.id=function(e) { return e.id; };
  606. opts.formatResultCssClass = function(data) { return data.css; }
  607. } else {
  608. if (!("query" in opts)) {
  609. if ("ajax" in opts) {
  610. ajaxUrl = opts.element.data("ajax-url");
  611. if (ajaxUrl && ajaxUrl.length > 0) {
  612. opts.ajax.url = ajaxUrl;
  613. }
  614. opts.query = ajax(opts.ajax);
  615. } else if ("data" in opts) {
  616. opts.query = local(opts.data);
  617. } else if ("tags" in opts) {
  618. opts.query = tags(opts.tags);
  619. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  620. opts.initSelection = function (element, callback) {
  621. var data = [];
  622. $(splitVal(element.val(), opts.separator)).each(function () {
  623. var id = this, text = this, tags=opts.tags;
  624. if ($.isFunction(tags)) tags=tags();
  625. $(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } });
  626. data.push({id: id, text: text});
  627. });
  628. callback(data);
  629. };
  630. }
  631. }
  632. }
  633. if (typeof(opts.query) !== "function") {
  634. throw "query function not defined for Select2 " + opts.element.attr("id");
  635. }
  636. return opts;
  637. },
  638. /**
  639. * Monitor the original element for changes and update select2 accordingly
  640. */
  641. // abstract
  642. monitorSource: function () {
  643. this.opts.element.bind("change.select2", this.bind(function (e) {
  644. if (this.opts.element.data("select2-change-triggered") !== true) {
  645. this.initSelection();
  646. }
  647. }));
  648. },
  649. /**
  650. * Triggers the change event on the source element
  651. */
  652. // abstract
  653. triggerChange: function (details) {
  654. details = details || {};
  655. details= $.extend({}, details, { type: "change", val: this.val() });
  656. // prevents recursive triggering
  657. this.opts.element.data("select2-change-triggered", true);
  658. this.opts.element.trigger(details);
  659. this.opts.element.data("select2-change-triggered", false);
  660. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  661. // so here we trigger the click event manually
  662. this.opts.element.click();
  663. },
  664. // abstract
  665. enable: function() {
  666. if (this.enabled) return;
  667. this.enabled=true;
  668. this.container.removeClass("select2-container-disabled");
  669. },
  670. // abstract
  671. disable: function() {
  672. if (!this.enabled) return;
  673. this.close();
  674. this.enabled=false;
  675. this.container.addClass("select2-container-disabled");
  676. },
  677. // abstract
  678. opened: function () {
  679. return this.container.hasClass("select2-dropdown-open");
  680. },
  681. // abstract
  682. positionDropdown: function() {
  683. var offset = this.container.offset(),
  684. height = this.container.outerHeight(),
  685. width = this.container.outerWidth(),
  686. dropHeight = this.dropdown.outerHeight(),
  687. viewportBottom = $(window).scrollTop() + document.documentElement.clientHeight,
  688. dropTop = offset.top + height,
  689. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  690. enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
  691. aboveNow = this.dropdown.hasClass("select2-drop-above"),
  692. above,
  693. css;
  694. // console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  695. // console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  696. // always prefer the current above/below alignment, unless there is not enough room
  697. if (aboveNow) {
  698. above = true;
  699. if (!enoughRoomAbove && enoughRoomBelow) above = false;
  700. } else {
  701. above = false;
  702. if (!enoughRoomBelow && enoughRoomAbove) above = true;
  703. }
  704. if (above) {
  705. dropTop = offset.top - dropHeight;
  706. this.container.addClass("select2-drop-above");
  707. this.dropdown.addClass("select2-drop-above");
  708. }
  709. else {
  710. this.container.removeClass("select2-drop-above");
  711. this.dropdown.removeClass("select2-drop-above");
  712. }
  713. css = {
  714. top:dropTop,
  715. left:offset.left,
  716. width:width
  717. };
  718. this.dropdown.css(css);
  719. },
  720. // abstract
  721. shouldOpen: function() {
  722. var event;
  723. if (this.opened()) return false;
  724. event = jQuery.Event("open");
  725. this.opts.element.trigger(event);
  726. return !event.isDefaultPrevented();
  727. },
  728. // abstract
  729. clearDropdownAlignmentPreference: function() {
  730. // clear the classes used to figure out the preference of where the dropdown should be opened
  731. this.container.removeClass("select2-drop-above");
  732. this.dropdown.removeClass("select2-drop-above");
  733. },
  734. /**
  735. * Opens the dropdown
  736. *
  737. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  738. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  739. */
  740. // abstract
  741. open: function () {
  742. if (!this.shouldOpen()) return false;
  743. window.setTimeout(this.bind(this.opening), 1);
  744. return true;
  745. },
  746. /**
  747. * Performs the opening of the dropdown
  748. */
  749. // abstract
  750. opening: function() {
  751. var cid = this.containerId, selector = "#"+ cid,
  752. scroll = "scroll." + cid, resize = "resize." + cid;
  753. this.container.parents().each(function() {
  754. $(this).bind(scroll, function() {
  755. var s2 = $(selector);
  756. if (s2.length == 0) {
  757. $(this).unbind(scroll);
  758. }
  759. s2.select2("close");
  760. });
  761. });
  762. $(window).bind(resize, function() {
  763. var s2 = $(selector);
  764. if (s2.length == 0) {
  765. $(window).unbind(resize);
  766. }
  767. s2.select2("close");
  768. });
  769. this.clearDropdownAlignmentPreference();
  770. if (this.search.val() === " ") { this.search.val(""); }
  771. this.dropdown.css(evaluate(this.opts.dropdownCss));
  772. this.dropdown.addClass("select2-drop-active");
  773. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  774. this.updateResults(true);
  775. if(this.dropdown[0] !== this.body().children().last()[0]) {
  776. this.dropdown.detach().appendTo(this.body());
  777. }
  778. this.dropdown.show();
  779. this.ensureHighlightVisible();
  780. this.positionDropdown();
  781. this.focusSearch();
  782. },
  783. // abstract
  784. close: function () {
  785. if (!this.opened()) return;
  786. var self = this;
  787. this.container.parents().each(function() {
  788. $(this).unbind("scroll." + self.containerId);
  789. });
  790. $(window).unbind("resize." + this.containerId);
  791. this.clearDropdownAlignmentPreference();
  792. this.dropdown.hide();
  793. this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
  794. this.results.empty();
  795. this.clearSearch();
  796. this.opts.element.trigger(jQuery.Event("close"));
  797. },
  798. // abstract
  799. clearSearch: function () {
  800. },
  801. // abstract
  802. ensureHighlightVisible: function () {
  803. var results = this.results, children, index, child, hb, rb, y, more;
  804. index = this.highlight();
  805. if (index < 0) return;
  806. if (index == 0) {
  807. // if the first element is highlighted scroll all the way to the top,
  808. // that way any unselectable headers above it will also be scrolled
  809. // into view
  810. results.scrollTop(0);
  811. return;
  812. }
  813. children = results.find(".select2-result-selectable");
  814. child = $(children[index]);
  815. hb = child.offset().top + child.outerHeight();
  816. // if this is the last child lets also make sure select2-more-results is visible
  817. if (index === children.length - 1) {
  818. more = results.find("li.select2-more-results");
  819. if (more.length > 0) {
  820. hb = more.offset().top + more.outerHeight();
  821. }
  822. }
  823. rb = results.offset().top + results.outerHeight();
  824. if (hb > rb) {
  825. results.scrollTop(results.scrollTop() + (hb - rb));
  826. }
  827. y = child.offset().top - results.offset().top;
  828. // make sure the top of the element is visible
  829. if (y < 0) {
  830. results.scrollTop(results.scrollTop() + y); // y is negative
  831. }
  832. },
  833. // abstract
  834. moveHighlight: function (delta) {
  835. var choices = this.results.find(".select2-result-selectable"),
  836. index = this.highlight();
  837. while (index > -1 && index < choices.length) {
  838. index += delta;
  839. var choice = $(choices[index]);
  840. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled")) {
  841. this.highlight(index);
  842. break;
  843. }
  844. }
  845. },
  846. // abstract
  847. highlight: function (index) {
  848. var choices = this.results.find(".select2-result-selectable").not(".select2-disabled");
  849. if (arguments.length === 0) {
  850. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  851. }
  852. if (index >= choices.length) index = choices.length - 1;
  853. if (index < 0) index = 0;
  854. choices.removeClass("select2-highlighted");
  855. $(choices[index]).addClass("select2-highlighted");
  856. this.ensureHighlightVisible();
  857. },
  858. // abstract
  859. countSelectableResults: function() {
  860. return this.results.find(".select2-result-selectable").not(".select2-disabled").length;
  861. },
  862. // abstract
  863. highlightUnderEvent: function (event) {
  864. var el = $(event.target).closest(".select2-result-selectable");
  865. if (el.length > 0 && !el.is(".select2-highlighted")) {
  866. var choices = this.results.find('.select2-result-selectable');
  867. this.highlight(choices.index(el));
  868. } else if (el.length == 0) {
  869. // if we are over an unselectable item remove al highlights
  870. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  871. }
  872. },
  873. // abstract
  874. loadMoreIfNeeded: function () {
  875. var results = this.results,
  876. more = results.find("li.select2-more-results"),
  877. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  878. offset = -1, // index of first element without data
  879. page = this.resultsPage + 1,
  880. self=this,
  881. term=this.search.val(),
  882. context=this.context;
  883. if (more.length === 0) return;
  884. below = more.offset().top - results.offset().top - results.height();
  885. if (below <= 0) {
  886. more.addClass("select2-active");
  887. this.opts.query({
  888. term: term,
  889. page: page,
  890. context: context,
  891. matcher: this.opts.matcher,
  892. callback: this.bind(function (data) {
  893. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  894. if (data.more===true) {
  895. more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
  896. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  897. } else {
  898. more.remove();
  899. }
  900. self.positionDropdown();
  901. self.resultsPage = page;
  902. })});
  903. }
  904. },
  905. /**
  906. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  907. */
  908. // abstract
  909. updateResults: function (initial) {
  910. var search = this.search, results = this.results, opts = this.opts, data, self=this;
  911. // if the search is currently hidden we do not alter the results
  912. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  913. return;
  914. }
  915. search.addClass("select2-active");
  916. function postRender() {
  917. results.scrollTop(0);
  918. search.removeClass("select2-active");
  919. self.positionDropdown();
  920. }
  921. function render(html) {
  922. results.html(escapeMarkup(html));
  923. postRender();
  924. }
  925. if (opts.maximumSelectionSize >=1) {
  926. data = this.data();
  927. if ($.isArray(data) && data.length >= opts.maximumSelectionSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  928. render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(opts.maximumSelectionSize) + "</li>");
  929. return;
  930. }
  931. }
  932. if (search.val().length < opts.minimumInputLength && checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  933. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  934. return;
  935. }
  936. else {
  937. render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
  938. }
  939. this.resultsPage = 1;
  940. opts.query({
  941. term: search.val(),
  942. page: this.resultsPage,
  943. context: null,
  944. matcher: opts.matcher,
  945. callback: this.bind(function (data) {
  946. var def; // default choice
  947. // save context, if any
  948. this.context = (data.context===undefined) ? null : data.context;
  949. // create a default choice and prepend it to the list
  950. if (this.opts.createSearchChoice && search.val() !== "") {
  951. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  952. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  953. if ($(data.results).filter(
  954. function () {
  955. return equal(self.id(this), self.id(def));
  956. }).length === 0) {
  957. data.results.unshift(def);
  958. }
  959. }
  960. }
  961. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  962. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  963. return;
  964. }
  965. results.empty();
  966. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  967. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  968. results.append("<li class='select2-more-results'>" + escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
  969. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  970. }
  971. this.postprocessResults(data, initial);
  972. postRender();
  973. })});
  974. },
  975. // abstract
  976. cancel: function () {
  977. this.close();
  978. },
  979. // abstract
  980. blur: function () {
  981. this.close();
  982. this.container.removeClass("select2-container-active");
  983. this.dropdown.removeClass("select2-drop-active");
  984. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  985. if (this.search[0] === document.activeElement) { this.search.blur(); }
  986. this.clearSearch();
  987. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  988. },
  989. // abstract
  990. focusSearch: function () {
  991. /* we do this in a timeout so that current event processing can complete before this code is executed.
  992. this makes sure the search field is focussed even if the current event would blur it */
  993. window.setTimeout(this.bind(function () {
  994. this.search.focus();
  995. // reset the value so IE places the cursor at the end of the input box
  996. this.search.val(this.search.val());
  997. }), 10);
  998. },
  999. // abstract
  1000. selectHighlighted: function () {
  1001. var index=this.highlight(),
  1002. highlighted=this.results.find(".select2-highlighted").not(".select2-disabled"),
  1003. data = highlighted.closest('.select2-result-selectable').data("select2-data");
  1004. if (data) {
  1005. highlighted.addClass("select2-disabled");
  1006. this.highlight(index);
  1007. this.onSelect(data);
  1008. }
  1009. },
  1010. // abstract
  1011. getPlaceholder: function () {
  1012. return this.opts.element.attr("placeholder") ||
  1013. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1014. this.opts.element.data("placeholder") ||
  1015. this.opts.placeholder;
  1016. },
  1017. /**
  1018. * Get the desired width for the container element. This is
  1019. * derived first from option `width` passed to select2, then
  1020. * the inline 'style' on the original element, and finally
  1021. * falls back to the jQuery calculated element width.
  1022. */
  1023. // abstract
  1024. initContainerWidth: function () {
  1025. function resolveContainerWidth() {
  1026. var style, attrs, matches, i, l;
  1027. if (this.opts.width === "off") {
  1028. return null;
  1029. } else if (this.opts.width === "element"){
  1030. return this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px';
  1031. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1032. // check if there is inline style on the element that contains width
  1033. style = this.opts.element.attr('style');
  1034. if (style !== undefined) {
  1035. attrs = style.split(';');
  1036. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1037. matches = attrs[i].replace(/\s/g, '')
  1038. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  1039. if (matches !== null && matches.length >= 1)
  1040. return matches[1];
  1041. }
  1042. }
  1043. if (this.opts.width === "resolve") {
  1044. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1045. // when attached to input type=hidden or elements hidden via css
  1046. style = this.opts.element.css('width');
  1047. if (style.indexOf("%") > 0) return style;
  1048. // finally, fallback on the calculated width of the element
  1049. return (this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px');
  1050. }
  1051. return null;
  1052. } else if ($.isFunction(this.opts.width)) {
  1053. return this.opts.width();
  1054. } else {
  1055. return this.opts.width;
  1056. }
  1057. };
  1058. var width = resolveContainerWidth.call(this);
  1059. if (width !== null) {
  1060. this.container.attr("style", "width: "+width);
  1061. }
  1062. }
  1063. });
  1064. SingleSelect2 = clazz(AbstractSelect2, {
  1065. // single
  1066. createContainer: function () {
  1067. var container = $("<div></div>", {
  1068. "class": "select2-container"
  1069. }).html([
  1070. " <a href='javascript:void(0)' class='select2-choice'>",
  1071. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  1072. " <div><b></b></div>" ,
  1073. "</a>",
  1074. " <div class='select2-drop select2-offscreen'>" ,
  1075. " <div class='select2-search'>" ,
  1076. " <input type='text' autocomplete='off' class='select2-input'/>" ,
  1077. " </div>" ,
  1078. " <ul class='select2-results'>" ,
  1079. " </ul>" ,
  1080. "</div>"].join(""));
  1081. return container;
  1082. },
  1083. // single
  1084. opening: function () {
  1085. this.search.show();
  1086. this.parent.opening.apply(this, arguments);
  1087. this.dropdown.removeClass("select2-offscreen");
  1088. },
  1089. // single
  1090. close: function () {
  1091. if (!this.opened()) return;
  1092. this.parent.close.apply(this, arguments);
  1093. this.dropdown.removeAttr("style").addClass("select2-offscreen").insertAfter(this.selection).show();
  1094. },
  1095. // single
  1096. focus: function () {
  1097. this.close();
  1098. this.selection.focus();
  1099. },
  1100. // single
  1101. isFocused: function () {
  1102. return this.selection[0] === document.activeElement;
  1103. },
  1104. // single
  1105. cancel: function () {
  1106. this.parent.cancel.apply(this, arguments);
  1107. this.selection.focus();
  1108. },
  1109. // single
  1110. initContainer: function () {
  1111. var selection,
  1112. container = this.container,
  1113. dropdown = this.dropdown,
  1114. clickingInside = false;
  1115. this.selection = selection = container.find(".select2-choice");
  1116. this.search.bind("keydown", this.bind(function (e) {
  1117. if (!this.enabled) return;
  1118. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1119. // prevent the page from scrolling
  1120. killEvent(e);
  1121. return;
  1122. }
  1123. if (this.opened()) {
  1124. switch (e.which) {
  1125. case KEY.UP:
  1126. case KEY.DOWN:
  1127. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1128. killEvent(e);
  1129. return;
  1130. case KEY.TAB:
  1131. case KEY.ENTER:
  1132. this.selectHighlighted();
  1133. killEvent(e);
  1134. return;
  1135. case KEY.ESC:
  1136. this.cancel(e);
  1137. killEvent(e);
  1138. return;
  1139. }
  1140. } else {
  1141. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1142. return;
  1143. }
  1144. this.open();
  1145. if (e.which === KEY.ENTER) {
  1146. // do not propagate the event otherwise we open, and propagate enter which closes
  1147. return;
  1148. }
  1149. }
  1150. }));
  1151. this.search.bind("focus", this.bind(function() {
  1152. this.selection.attr("tabIndex", "-1");
  1153. }));
  1154. this.search.bind("blur", this.bind(function() {
  1155. if (!this.opened()) this.container.removeClass("select2-container-active");
  1156. window.setTimeout(this.bind(function() { this.selection.attr("tabIndex", this.opts.element.attr("tabIndex")); }), 10);
  1157. }));
  1158. selection.bind("mousedown", this.bind(function (e) {
  1159. clickingInside = true;
  1160. if (this.opened()) {
  1161. this.close();
  1162. this.selection.focus();
  1163. } else if (this.enabled) {
  1164. this.open();
  1165. }
  1166. clickingInside = false;
  1167. }));
  1168. dropdown.bind("mousedown", this.bind(function() { this.search.focus(); }));
  1169. selection.bind("focus", this.bind(function() {
  1170. this.container.addClass("select2-container-active");
  1171. // hide the search so the tab key does not focus on it
  1172. this.search.attr("tabIndex", "-1");
  1173. }));
  1174. selection.bind("blur", this.bind(function() {
  1175. if (!this.opened()) {
  1176. this.container.removeClass("select2-container-active");
  1177. }
  1178. window.setTimeout(this.bind(function() { this.search.attr("tabIndex", this.opts.element.attr("tabIndex")); }), 10);
  1179. }));
  1180. selection.bind("keydown", this.bind(function(e) {
  1181. if (!this.enabled) return;
  1182. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1183. // prevent the page from scrolling
  1184. killEvent(e);
  1185. return;
  1186. }
  1187. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  1188. || e.which === KEY.ESC || e.which == KEY.ENTER) {
  1189. return;
  1190. }
  1191. if (e.which == KEY.DELETE) {
  1192. if (this.opts.allowClear) {
  1193. this.clear();
  1194. }
  1195. return;
  1196. }
  1197. this.open();
  1198. if (e.which === KEY.ENTER) {
  1199. // do not propagate the event otherwise we open, and propagate enter which closes
  1200. killEvent(e);
  1201. return;
  1202. }
  1203. // do not set the search input value for non-alpha-numeric keys
  1204. // otherwise pressing down results in a '(' being set in the search field
  1205. if (e.which < 48 ) { // '0' == 48
  1206. killEvent(e);
  1207. return;
  1208. }
  1209. var keyWritten = String.fromCharCode(e.which).toLowerCase();
  1210. if (e.shiftKey) {
  1211. keyWritten = keyWritten.toUpperCase();
  1212. }
  1213. this.search.val(keyWritten);
  1214. // prevent event propagation so it doesnt replay on the now focussed search field and result in double key entry
  1215. killEvent(e);
  1216. }));
  1217. selection.delegate("abbr", "mousedown", this.bind(function (e) {
  1218. if (!this.enabled) return;
  1219. this.clear();
  1220. killEvent(e);
  1221. this.close();
  1222. this.triggerChange();
  1223. this.selection.focus();
  1224. }));
  1225. this.setPlaceholder();
  1226. this.search.bind("focus", this.bind(function() {
  1227. this.container.addClass("select2-container-active");
  1228. }));
  1229. },
  1230. // single
  1231. clear: function() {
  1232. this.opts.element.val("");
  1233. this.selection.find("span").empty();
  1234. this.selection.removeData("select2-data");
  1235. this.setPlaceholder();
  1236. },
  1237. /**
  1238. * Sets selection based on source element's value
  1239. */
  1240. // single
  1241. initSelection: function () {
  1242. var selected;
  1243. if (this.opts.element.val() === "") {
  1244. this.close();
  1245. this.setPlaceholder();
  1246. } else {
  1247. var self = this;
  1248. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1249. if (selected !== undefined && selected !== null) {
  1250. self.updateSelection(selected);
  1251. self.close();
  1252. self.setPlaceholder();
  1253. }
  1254. });
  1255. }
  1256. },
  1257. // single
  1258. prepareOpts: function () {
  1259. var opts = this.parent.prepareOpts.apply(this, arguments);
  1260. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1261. // install the selection initializer
  1262. opts.initSelection = function (element, callback) {
  1263. var selected = element.find(":selected");
  1264. // a single select box always has a value, no need to null check 'selected'
  1265. if ($.isFunction(callback))
  1266. callback({id: selected.attr("value"), text: selected.text()});
  1267. };
  1268. }
  1269. return opts;
  1270. },
  1271. // single
  1272. setPlaceholder: function () {
  1273. var placeholder = this.getPlaceholder();
  1274. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1275. // check for a first blank option if attached to a select
  1276. if (this.select && this.select.find("option:first").text() !== "") return;
  1277. this.selection.find("span").html(escapeMarkup(placeholder));
  1278. this.selection.addClass("select2-default");
  1279. this.selection.find("abbr").hide();
  1280. }
  1281. },
  1282. // single
  1283. postprocessResults: function (data, initial) {
  1284. var selected = 0, self = this, showSearchInput = true;
  1285. // find the selected element in the result list
  1286. this.results.find(".select2-result-selectable").each2(function (i, elm) {
  1287. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1288. selected = i;
  1289. return false;
  1290. }
  1291. });
  1292. // and highlight it
  1293. this.highlight(selected);
  1294. // hide the search box if this is the first we got the results and there are a few of them
  1295. if (initial === true) {
  1296. showSearchInput = this.showSearchInput = countResults(data.results) >= this.opts.minimumResultsForSearch;
  1297. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1298. //add "select2-with-searchbox" to the container if search box is shown
  1299. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1300. }
  1301. },
  1302. // single
  1303. onSelect: function (data) {
  1304. var old = this.opts.element.val();
  1305. this.opts.element.val(this.id(data));
  1306. this.updateSelection(data);
  1307. this.close();
  1308. this.selection.focus();
  1309. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1310. },
  1311. // single
  1312. updateSelection: function (data) {
  1313. var container=this.selection.find("span"), formatted;
  1314. this.selection.data("select2-data", data);
  1315. container.empty();
  1316. formatted=this.opts.formatSelection(data, container);
  1317. if (formatted !== undefined) {
  1318. container.append(escapeMarkup(formatted));
  1319. }
  1320. this.selection.removeClass("select2-default");
  1321. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1322. this.selection.find("abbr").show();
  1323. }
  1324. },
  1325. // single
  1326. val: function () {
  1327. var val, data = null, self = this;
  1328. if (arguments.length === 0) {
  1329. return this.opts.element.val();
  1330. }
  1331. val = arguments[0];
  1332. if (this.select) {
  1333. this.select
  1334. .val(val)
  1335. .find(":selected").each2(function (i, elm) {
  1336. data = {id: elm.attr("value"), text: elm.text()};
  1337. return false;
  1338. });
  1339. this.updateSelection(data);
  1340. this.setPlaceholder();
  1341. } else {
  1342. if (this.opts.initSelection === undefined) {
  1343. throw new Error("cannot call val() if initSelection() is not defined");
  1344. }
  1345. // val is an id. !val is true for [undefined,null,'']
  1346. if (!val) {
  1347. this.clear();
  1348. return;
  1349. }
  1350. this.opts.initSelection(this.opts.element, function(data){
  1351. self.opts.element.val(!data ? "" : self.id(data));
  1352. self.updateSelection(data);
  1353. self.setPlaceholder();
  1354. });
  1355. }
  1356. },
  1357. // single
  1358. clearSearch: function () {
  1359. this.search.val("");
  1360. },
  1361. // single
  1362. data: function(value) {
  1363. var data;
  1364. if (arguments.length === 0) {
  1365. data = this.selection.data("select2-data");
  1366. if (data == undefined) data = null;
  1367. return data;
  1368. } else {
  1369. if (!value || value === "") {
  1370. this.clear();
  1371. } else {
  1372. this.opts.element.val(!value ? "" : this.id(value));
  1373. this.updateSelection(value);
  1374. }
  1375. }
  1376. }
  1377. });
  1378. MultiSelect2 = clazz(AbstractSelect2, {
  1379. // multi
  1380. createContainer: function () {
  1381. var container = $("<div></div>", {
  1382. "class": "select2-container select2-container-multi"
  1383. }).html([
  1384. " <ul class='select2-choices'>",
  1385. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1386. " <li class='select2-search-field'>" ,
  1387. " <input type='text' autocomplete='off' class='select2-input'>" ,
  1388. " </li>" ,
  1389. "</ul>" ,
  1390. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1391. " <ul class='select2-results'>" ,
  1392. " </ul>" ,
  1393. "</div>"].join(""));
  1394. return container;
  1395. },
  1396. // multi
  1397. prepareOpts: function () {
  1398. var opts = this.parent.prepareOpts.apply(this, arguments);
  1399. // TODO validate placeholder is a string if specified
  1400. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1401. // install sthe selection initializer
  1402. opts.initSelection = function (element,callback) {
  1403. var data = [];
  1404. element.find(":selected").each2(function (i, elm) {
  1405. data.push({id: elm.attr("value"), text: elm.text()});
  1406. });
  1407. if ($.isFunction(callback))
  1408. callback(data);
  1409. };
  1410. }
  1411. return opts;
  1412. },
  1413. // multi
  1414. initContainer: function () {
  1415. var selector = ".select2-choices", selection;
  1416. this.searchContainer = this.container.find(".select2-search-field");
  1417. this.selection = selection = this.container.find(selector);
  1418. this.search.bind("keydown", this.bind(function (e) {
  1419. if (!this.enabled) return;
  1420. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1421. this.close();
  1422. var choices,
  1423. selected = selection.find(".select2-search-choice-focus");
  1424. if (selected.length > 0) {
  1425. this.unselect(selected.first());
  1426. this.search.width(10);
  1427. killEvent(e);
  1428. return;
  1429. }
  1430. choices = selection.find(".select2-search-choice");
  1431. if (choices.length > 0) {
  1432. choices.last().addClass("select2-search-choice-focus");
  1433. }
  1434. } else {
  1435. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1436. }
  1437. if (this.opened()) {
  1438. switch (e.which) {
  1439. case KEY.UP:
  1440. case KEY.DOWN:
  1441. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1442. killEvent(e);
  1443. return;
  1444. case KEY.ENTER:
  1445. case KEY.TAB:
  1446. this.selectHighlighted();
  1447. killEvent(e);
  1448. return;
  1449. case KEY.ESC:
  1450. this.cancel(e);
  1451. killEvent(e);
  1452. return;
  1453. }
  1454. }
  1455. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  1456. || e.which === KEY.BACKSPACE || e.which === KEY.ESC || e.which === KEY.ENTER) {
  1457. return;
  1458. }
  1459. this.open();
  1460. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1461. // prevent the page from scrolling
  1462. killEvent(e);
  1463. }
  1464. }));
  1465. this.search.bind("keyup", this.bind(this.resizeSearch));
  1466. this.search.bind("blur", this.bind(function() {
  1467. this.container.removeClass("select2-container-active");
  1468. }));
  1469. this.container.delegate(selector, "mousedown", this.bind(function (e) {
  1470. if (!this.enabled) return;
  1471. this.clearPlaceholder();
  1472. this.open();
  1473. this.focusSearch();
  1474. e.preventDefault();
  1475. }));
  1476. this.container.delegate(selector, "focus", this.bind(function () {
  1477. if (!this.enabled) return;
  1478. this.container.addClass("select2-container-active");
  1479. this.dropdown.addClass("select2-drop-active");
  1480. this.clearPlaceholder();
  1481. }));
  1482. // set the placeholder if necessary
  1483. this.clearSearch();
  1484. },
  1485. // multi
  1486. enable: function() {
  1487. if (this.enabled) return;
  1488. this.parent.enable.apply(this, arguments);
  1489. this.search.removeAttr("disabled");
  1490. },
  1491. // multi
  1492. disable: function() {
  1493. if (!this.enabled) return;
  1494. this.parent.disable.apply(this, arguments);
  1495. this.search.attr("disabled", true);
  1496. },
  1497. // multi
  1498. initSelection: function () {
  1499. var data;
  1500. if (this.opts.element.val() === "") {
  1501. this.updateSelection([]);
  1502. this.close();
  1503. // set the placeholder if necessary
  1504. this.clearSearch();
  1505. }
  1506. if (this.select || this.opts.element.val() !== "") {
  1507. var self = this;
  1508. this.opts.initSelection.call(null, this.opts.element, function(data){
  1509. if (data !== undefined && data !== null) {
  1510. self.updateSelection(data);
  1511. self.close();
  1512. // set the placeholder if necessary
  1513. self.clearSearch();
  1514. }
  1515. });
  1516. }
  1517. },
  1518. // multi
  1519. clearSearch: function () {
  1520. var placeholder = this.getPlaceholder();
  1521. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1522. this.search.val(placeholder).addClass("select2-default");
  1523. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1524. this.resizeSearch();
  1525. } else {
  1526. // we set this to " " instead of "" and later clear it on focus() because there is a firefox bug
  1527. // that does not properly render the caret when the field starts out blank
  1528. this.search.val(" ").width(10);
  1529. }
  1530. },
  1531. // multi
  1532. clearPlaceholder: function () {
  1533. if (this.search.hasClass("select2-default")) {
  1534. this.search.val("").removeClass("select2-default");
  1535. } else {
  1536. // work around for the space character we set to avoid firefox caret bug
  1537. if (this.search.val() === " ") this.search.val("");
  1538. }
  1539. },
  1540. // multi
  1541. opening: function () {
  1542. this.parent.opening.apply(this, arguments);
  1543. this.clearPlaceholder();
  1544. this.resizeSearch();
  1545. this.focusSearch();
  1546. },
  1547. // multi
  1548. close: function () {
  1549. if (!this.opened()) return;
  1550. this.parent.close.apply(this, arguments);
  1551. },
  1552. // multi
  1553. focus: function () {
  1554. this.close();
  1555. this.search.focus();
  1556. },
  1557. // multi
  1558. isFocused: function () {
  1559. return this.search.hasClass("select2-focused");
  1560. },
  1561. // multi
  1562. updateSelection: function (data) {
  1563. var ids = [], filtered = [], self = this;
  1564. // filter out duplicates
  1565. $(data).each(function () {
  1566. if (indexOf(self.id(this), ids) < 0) {
  1567. ids.push(self.id(this));
  1568. filtered.push(this);
  1569. }
  1570. });
  1571. data = filtered;
  1572. this.selection.find(".select2-search-choice").remove();
  1573. $(data).each(function () {
  1574. self.addSelectedChoice(this);
  1575. });
  1576. self.postprocessResults();
  1577. },
  1578. // multi
  1579. onSelect: function (data) {
  1580. this.addSelectedChoice(data);
  1581. if (this.select) { this.postprocessResults(); }
  1582. if (this.opts.closeOnSelect) {
  1583. this.close();
  1584. this.search.width(10);
  1585. } else {
  1586. this.search.width(10);
  1587. this.resizeSearch();
  1588. if (this.countSelectableResults()>0) {
  1589. this.positionDropdown();
  1590. } else {
  1591. // if nothing left to select close
  1592. this.close();
  1593. }
  1594. }
  1595. // since its not possible to select an element that has already been
  1596. // added we do not need to check if this is a new element before firing change
  1597. this.triggerChange({ added: data });
  1598. this.focusSearch();
  1599. },
  1600. // multi
  1601. cancel: function () {
  1602. this.close();
  1603. this.focusSearch();
  1604. },
  1605. // multi
  1606. addSelectedChoice: function (data) {
  1607. var choice=$(
  1608. "<li class='select2-search-choice'>" +
  1609. " <div></div>" +
  1610. " <a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>" +
  1611. "</li>"),
  1612. id = this.id(data),
  1613. val = this.getVal(),
  1614. formatted;
  1615. formatted=this.opts.formatSelection(data, choice);
  1616. choice.find("div").replaceWith("<div>"+escapeMarkup(formatted)+"</div>");
  1617. choice.find(".select2-search-choice-close")
  1618. .bind("mousedown", killEvent)
  1619. .bind("click dblclick", this.bind(function (e) {
  1620. if (!this.enabled) return;
  1621. $(e.target).closest(".select2-search-choice").fadeOut('fast').animate({width: "hide"}, 50, this.bind(function(){
  1622. this.unselect($(e.target));
  1623. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1624. this.close();
  1625. this.focusSearch();
  1626. })).dequeue();
  1627. killEvent(e);
  1628. })).bind("focus", this.bind(function () {
  1629. if (!this.enabled) return;
  1630. this.container.addClass("select2-container-active");
  1631. this.dropdown.addClass("select2-drop-active");
  1632. }));
  1633. choice.data("select2-data", data);
  1634. choice.insertBefore(this.searchContainer);
  1635. val.push(id);
  1636. this.setVal(val);
  1637. },
  1638. // multi
  1639. unselect: function (selected) {
  1640. var val = this.getVal(),
  1641. data,
  1642. index;
  1643. selected = selected.closest(".select2-search-choice");
  1644. if (selected.length === 0) {
  1645. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1646. }
  1647. data = selected.data("select2-data");
  1648. index = indexOf(this.id(data), val);
  1649. if (index >= 0) {
  1650. val.splice(index, 1);
  1651. this.setVal(val);
  1652. if (this.select) this.postprocessResults();
  1653. }
  1654. selected.remove();
  1655. this.triggerChange({ removed: data });
  1656. },
  1657. // multi
  1658. postprocessResults: function () {
  1659. var val = this.getVal(),
  1660. choices = this.results.find(".select2-result-selectable"),
  1661. compound = this.results.find(".select2-result-with-children"),
  1662. self = this;
  1663. choices.each2(function (i, choice) {
  1664. var id = self.id(choice.data("select2-data"));
  1665. if (indexOf(id, val) >= 0) {
  1666. choice.addClass("select2-disabled").removeClass("select2-result-selectable");
  1667. } else {
  1668. choice.removeClass("select2-disabled").addClass("select2-result-selectable");
  1669. }
  1670. });
  1671. compound.each2(function(i, e) {
  1672. if (e.find(".select2-result-selectable").length==0) {
  1673. e.addClass("select2-disabled");
  1674. } else {
  1675. e.removeClass("select2-disabled");
  1676. }
  1677. });
  1678. choices.each2(function (i, choice) {
  1679. if (!choice.hasClass("select2-disabled") && choice.hasClass("select2-result-selectable")) {
  1680. self.highlight(0);
  1681. return false;
  1682. }
  1683. });
  1684. },
  1685. // multi
  1686. resizeSearch: function () {
  1687. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  1688. sideBorderPadding = getSideBorderPadding(this.search);
  1689. minimumWidth = measureTextWidth(this.search) + 10;
  1690. left = this.search.offset().left;
  1691. maxWidth = this.selection.width();
  1692. containerLeft = this.selection.offset().left;
  1693. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  1694. if (searchWidth < minimumWidth) {
  1695. searchWidth = maxWidth - sideBorderPadding;
  1696. }
  1697. if (searchWidth < 40) {
  1698. searchWidth = maxWidth - sideBorderPadding;
  1699. }
  1700. this.search.width(searchWidth);
  1701. },
  1702. // multi
  1703. getVal: function () {
  1704. var val;
  1705. if (this.select) {
  1706. val = this.select.val();
  1707. return val === null ? [] : val;
  1708. } else {
  1709. val = this.opts.element.val();
  1710. return splitVal(val, this.opts.separator);
  1711. }
  1712. },
  1713. // multi
  1714. setVal: function (val) {
  1715. var unique;
  1716. if (this.select) {
  1717. this.select.val(val);
  1718. } else {
  1719. unique = [];
  1720. // filter out duplicates
  1721. $(val).each(function () {
  1722. if (indexOf(this, unique) < 0) unique.push(this);
  1723. });
  1724. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  1725. }
  1726. },
  1727. // multi
  1728. val: function () {
  1729. var val, data = [], self=this;
  1730. if (arguments.length === 0) {
  1731. return this.getVal();
  1732. }
  1733. val = arguments[0];
  1734. if (!val) {
  1735. this.opts.element.val("");
  1736. this.updateSelection([]);
  1737. this.clearSearch();
  1738. return;
  1739. }
  1740. // val is a list of ids
  1741. this.setVal(val);
  1742. if (this.select) {
  1743. this.select.find(":selected").each(function () {
  1744. data.push({id: $(this).attr("value"), text: $(this).text()});
  1745. });
  1746. this.updateSelection(data);
  1747. } else {
  1748. if (this.opts.initSelection === undefined) {
  1749. throw new Error("val() cannot be called if initSelection() is not defined")
  1750. }
  1751. this.opts.initSelection(this.opts.element, function(data){
  1752. var ids=$(data).map(self.id);
  1753. self.setVal(ids);
  1754. self.updateSelection(data);
  1755. self.clearSearch();
  1756. });
  1757. }
  1758. this.clearSearch();
  1759. },
  1760. // multi
  1761. onSortStart: function() {
  1762. if (this.select) {
  1763. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  1764. }
  1765. // collapse search field into 0 width so its container can be collapsed as well
  1766. this.search.width(0);
  1767. // hide the container
  1768. this.searchContainer.hide();
  1769. },
  1770. // multi
  1771. onSortEnd:function() {
  1772. var val=[], self=this;
  1773. // show search and move it to the end of the list
  1774. this.searchContainer.show();
  1775. // make sure the search container is the last item in the list
  1776. this.searchContainer.appendTo(this.searchContainer.parent());
  1777. // since we collapsed the width in dragStarted, we resize it here
  1778. this.resizeSearch();
  1779. // update selection
  1780. this.selection.find(".select2-search-choice").each(function() {
  1781. val.push(self.opts.id($(this).data("select2-data")));
  1782. });
  1783. this.setVal(val);
  1784. this.triggerChange();
  1785. },
  1786. // multi
  1787. data: function(values) {
  1788. var self=this, ids;
  1789. if (arguments.length === 0) {
  1790. return this.selection
  1791. .find(".select2-search-choice")
  1792. .map(function() { return $(this).data("select2-data"); })
  1793. .get();
  1794. } else {
  1795. if (!values) { values = []; }
  1796. ids = $.map(values, function(e) { return self.opts.id(e)});
  1797. this.setVal(ids);
  1798. this.updateSelection(values);
  1799. this.clearSearch();
  1800. }
  1801. }
  1802. });
  1803. $.fn.select2 = function () {
  1804. var args = Array.prototype.slice.call(arguments, 0),
  1805. opts,
  1806. select2,
  1807. value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
  1808. this.each(function () {
  1809. if (args.length === 0 || typeof(args[0]) === "object") {
  1810. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1811. opts.element = $(this);
  1812. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1813. multiple = opts.element.attr("multiple");
  1814. } else {
  1815. multiple = opts.multiple || false;
  1816. if ("tags" in opts) {opts.multiple = multiple = true;}
  1817. }
  1818. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1819. select2.init(opts);
  1820. } else if (typeof(args[0]) === "string") {
  1821. if (indexOf(args[0], allowedMethods) < 0) {
  1822. throw "Unknown method: " + args[0];
  1823. }
  1824. value = undefined;
  1825. select2 = $(this).data("select2");
  1826. if (select2 === undefined) return;
  1827. if (args[0] === "container") {
  1828. value=select2.container;
  1829. } else {
  1830. value = select2[args[0]].apply(select2, args.slice(1));
  1831. }
  1832. if (value !== undefined) {return false;}
  1833. } else {
  1834. throw "Invalid arguments to select2 plugin: " + args;
  1835. }
  1836. });
  1837. return (value === undefined) ? this : value;
  1838. };
  1839. // plugin defaults, accessible to users
  1840. $.fn.select2.defaults = {
  1841. width: "copy",
  1842. closeOnSelect: true,
  1843. containerCss: {},
  1844. dropdownCss: {},
  1845. containerCssClass: "",
  1846. dropdownCssClass: "",
  1847. formatResult: function(result, container, query) {
  1848. var markup=[];
  1849. markMatch(result.text, query.term, markup);
  1850. return markup.join("");
  1851. },
  1852. formatSelection: function (data, container) {
  1853. return data.text;
  1854. },
  1855. formatResultCssClass: function(data) {return undefined;},
  1856. formatNoMatches: function () { return "No matches found"; },
  1857. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  1858. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " items"; },
  1859. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  1860. formatSearching: function () { return "Searching..."; },
  1861. minimumResultsForSearch: 0,
  1862. minimumInputLength: 0,
  1863. maximumSelectionSize: 0,
  1864. id: function (e) { return e.id; },
  1865. matcher: function(term, text) {
  1866. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  1867. }
  1868. };
  1869. // exports
  1870. window.Select2 = {
  1871. query: {
  1872. ajax: ajax,
  1873. local: local,
  1874. tags: tags
  1875. }, util: {
  1876. debounce: debounce,
  1877. markMatch: markMatch
  1878. }, "class": {
  1879. "abstract": AbstractSelect2,
  1880. "single": SingleSelect2,
  1881. "multi": MultiSelect2
  1882. }
  1883. };
  1884. }(jQuery));