select2.js 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818
  1. /*
  2. Copyright 2012 Igor Vaynberg
  3. Version: @@ver@@ Timestamp: @@timestamp@@
  4. This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
  5. General Public License version 2 (the "GPL License"). You may choose either license to govern your
  6. use of this software only upon the condition that you accept all of the terms of either the Apache
  7. License or the GPL License.
  8. You may obtain a copy of the Apache License and the GPL License at:
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. http://www.gnu.org/licenses/gpl-2.0.html
  11. Unless required by applicable law or agreed to in writing, software distributed under the
  12. Apache License or the GPL Licesnse is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for
  14. the specific language governing permissions and limitations under the Apache License and the GPL License.
  15. */
  16. (function ($) {
  17. if(typeof $.fn.each2 == "undefined"){
  18. $.fn.extend({
  19. /*
  20. * 4-10 times faster .each replacement
  21. * use it carefully, as it overrides jQuery context of element on each iteration
  22. */
  23. each2 : function (c) {
  24. var j = $([0]), i = -1, l = this.length;
  25. while (
  26. ++i < l
  27. && (j.context = j[0] = this[i])
  28. && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
  29. );
  30. return this;
  31. }
  32. });
  33. }
  34. })(jQuery);
  35. (function ($, undefined) {
  36. "use strict";
  37. /*global document, window, jQuery, console */
  38. if (window.Select2 !== undefined) {
  39. return;
  40. }
  41. var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer,
  42. lastMousePosition, $document, scrollBarDimensions,
  43. KEY = {
  44. TAB: 9,
  45. ENTER: 13,
  46. ESC: 27,
  47. SPACE: 32,
  48. LEFT: 37,
  49. UP: 38,
  50. RIGHT: 39,
  51. DOWN: 40,
  52. SHIFT: 16,
  53. CTRL: 17,
  54. ALT: 18,
  55. PAGE_UP: 33,
  56. PAGE_DOWN: 34,
  57. HOME: 36,
  58. END: 35,
  59. BACKSPACE: 8,
  60. DELETE: 46,
  61. isArrow: function (k) {
  62. k = k.which ? k.which : k;
  63. switch (k) {
  64. case KEY.LEFT:
  65. case KEY.RIGHT:
  66. case KEY.UP:
  67. case KEY.DOWN:
  68. return true;
  69. }
  70. return false;
  71. },
  72. isControl: function (e) {
  73. var k = e.which;
  74. switch (k) {
  75. case KEY.SHIFT:
  76. case KEY.CTRL:
  77. case KEY.ALT:
  78. return true;
  79. }
  80. if (e.metaKey) return true;
  81. return false;
  82. },
  83. isFunctionKey: function (k) {
  84. k = k.which ? k.which : k;
  85. return k >= 112 && k <= 123;
  86. }
  87. },
  88. MEASURE_SCROLLBAR_TEMPLATE = "<div style='position:absolute; top:-10000px; left:-10000px; width:100px; height:100px; overflow:scroll;'></div>";
  89. $document = $(document);
  90. nextUid=(function() { var counter=1; return function() { return counter++; }; }());
  91. function indexOf(value, array) {
  92. var i = 0, l = array.length;
  93. for (; i < l; i = i + 1) {
  94. if (equal(value, array[i])) return i;
  95. }
  96. return -1;
  97. }
  98. function measureScrollbar () {
  99. var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
  100. $template.appendTo('body');
  101. var dim = {
  102. width: $template.width() - $template[0].clientWidth,
  103. height: $template.height() - $template[0].clientHeight
  104. };
  105. $template.remove();
  106. return dim;
  107. }
  108. /**
  109. * Compares equality of a and b
  110. * @param a
  111. * @param b
  112. */
  113. function equal(a, b) {
  114. if (a === b) return true;
  115. if (a === undefined || b === undefined) return false;
  116. if (a === null || b === null) return false;
  117. if (a.constructor === String) return a+'' === b+''; // IE requires a+'' instead of just a
  118. if (b.constructor === String) return b+'' === a+''; // IE requires b+'' instead of just b
  119. return false;
  120. }
  121. /**
  122. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  123. * strings
  124. * @param string
  125. * @param separator
  126. */
  127. function splitVal(string, separator) {
  128. var val, i, l;
  129. if (string === null || string.length < 1) return [];
  130. val = string.split(separator);
  131. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  132. return val;
  133. }
  134. function getSideBorderPadding(element) {
  135. return element.outerWidth(false) - element.width();
  136. }
  137. function installKeyUpChangeEvent(element) {
  138. var key="keyup-change-value";
  139. element.bind("keydown", function () {
  140. if ($.data(element, key) === undefined) {
  141. $.data(element, key, element.val());
  142. }
  143. });
  144. element.bind("keyup", function () {
  145. var val= $.data(element, key);
  146. if (val !== undefined && element.val() !== val) {
  147. $.removeData(element, key);
  148. element.trigger("keyup-change");
  149. }
  150. });
  151. }
  152. $document.bind("mousemove", function (e) {
  153. lastMousePosition = {x: e.pageX, y: e.pageY};
  154. });
  155. /**
  156. * filters mouse events so an event is fired only if the mouse moved.
  157. *
  158. * filters out mouse events that occur when mouse is stationary but
  159. * the elements under the pointer are scrolled.
  160. */
  161. function installFilteredMouseMove(element) {
  162. element.bind("mousemove", function (e) {
  163. var lastpos = lastMousePosition;
  164. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  165. $(e.target).trigger("mousemove-filtered", e);
  166. }
  167. });
  168. }
  169. /**
  170. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  171. * within the last quietMillis milliseconds.
  172. *
  173. * @param quietMillis number of milliseconds to wait before invoking fn
  174. * @param fn function to be debounced
  175. * @param ctx object to be used as this reference within fn
  176. * @return debounced version of fn
  177. */
  178. function debounce(quietMillis, fn, ctx) {
  179. ctx = ctx || undefined;
  180. var timeout;
  181. return function () {
  182. var args = arguments;
  183. window.clearTimeout(timeout);
  184. timeout = window.setTimeout(function() {
  185. fn.apply(ctx, args);
  186. }, quietMillis);
  187. };
  188. }
  189. /**
  190. * A simple implementation of a thunk
  191. * @param formula function used to lazily initialize the thunk
  192. * @return {Function}
  193. */
  194. function thunk(formula) {
  195. var evaluated = false,
  196. value;
  197. return function() {
  198. if (evaluated === false) { value = formula(); evaluated = true; }
  199. return value;
  200. };
  201. };
  202. function installDebouncedScroll(threshold, element) {
  203. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  204. element.bind("scroll", function (e) {
  205. if (indexOf(e.target, element.get()) >= 0) notify(e);
  206. });
  207. }
  208. function focus($el) {
  209. if ($el[0] === document.activeElement) return;
  210. /* set the focus in a 0 timeout - that way the focus is set after the processing
  211. of the current event has finished - which seems like the only reliable way
  212. to set focus */
  213. window.setTimeout(function() {
  214. var el=$el[0], pos=$el.val().length, range;
  215. $el.focus();
  216. /* make sure el received focus so we do not error out when trying to manipulate the caret.
  217. sometimes modals or others listeners may steal it after its set */
  218. if ($el.is(":visible") && el === document.activeElement) {
  219. /* after the focus is set move the caret to the end, necessary when we val()
  220. just before setting focus */
  221. if(el.setSelectionRange)
  222. {
  223. el.setSelectionRange(pos, pos);
  224. }
  225. else if (el.createTextRange) {
  226. range = el.createTextRange();
  227. range.collapse(false);
  228. range.select();
  229. }
  230. }
  231. }, 0);
  232. }
  233. function killEvent(event) {
  234. event.preventDefault();
  235. event.stopPropagation();
  236. }
  237. function killEventImmediately(event) {
  238. event.preventDefault();
  239. event.stopImmediatePropagation();
  240. }
  241. function measureTextWidth(e) {
  242. if (!sizer){
  243. var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
  244. sizer = $(document.createElement("div")).css({
  245. position: "absolute",
  246. left: "-10000px",
  247. top: "-10000px",
  248. display: "none",
  249. fontSize: style.fontSize,
  250. fontFamily: style.fontFamily,
  251. fontStyle: style.fontStyle,
  252. fontWeight: style.fontWeight,
  253. letterSpacing: style.letterSpacing,
  254. textTransform: style.textTransform,
  255. whiteSpace: "nowrap"
  256. });
  257. sizer.attr("class","select2-sizer");
  258. $("body").append(sizer);
  259. }
  260. sizer.text(e.val());
  261. return sizer.width();
  262. }
  263. function syncCssClasses(dest, src, adapter) {
  264. var classes, replacements = [], adapted;
  265. classes = dest.attr("class");
  266. if (classes) {
  267. classes = '' + classes; // for IE which returns object
  268. $(classes.split(" ")).each2(function() {
  269. if (this.indexOf("select2-") === 0) {
  270. replacements.push(this);
  271. }
  272. });
  273. }
  274. classes = src.attr("class");
  275. if (classes) {
  276. classes = '' + classes; // for IE which returns object
  277. $(classes.split(" ")).each2(function() {
  278. if (this.indexOf("select2-") !== 0) {
  279. adapted = adapter(this);
  280. if (adapted) {
  281. replacements.push(this);
  282. }
  283. }
  284. });
  285. }
  286. dest.attr("class", replacements.join(" "));
  287. }
  288. function markMatch(text, term, markup, escapeMarkup) {
  289. var match=text.toUpperCase().indexOf(term.toUpperCase()),
  290. tl=term.length;
  291. if (match<0) {
  292. markup.push(escapeMarkup(text));
  293. return;
  294. }
  295. markup.push(escapeMarkup(text.substring(0, match)));
  296. markup.push("<span class='select2-match'>");
  297. markup.push(escapeMarkup(text.substring(match, match + tl)));
  298. markup.push("</span>");
  299. markup.push(escapeMarkup(text.substring(match + tl, text.length)));
  300. }
  301. /**
  302. * Produces an ajax-based query function
  303. *
  304. * @param options object containing configuration paramters
  305. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  306. * @param options.url url for the data
  307. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  308. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
  309. * @param options.traditional a boolean flag that should be true if you wish to use the traditional style of param serialization for the ajax request
  310. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  311. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  312. * The expected format is an object containing the following keys:
  313. * results array of objects that will be used as choices
  314. * more (optional) boolean indicating whether there are more results available
  315. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  316. */
  317. function ajax(options) {
  318. var timeout, // current scheduled but not yet executed request
  319. requestSequence = 0, // sequence used to drop out-of-order responses
  320. handler = null,
  321. quietMillis = options.quietMillis || 100,
  322. ajaxUrl = options.url,
  323. self = this;
  324. return function (query) {
  325. window.clearTimeout(timeout);
  326. timeout = window.setTimeout(function () {
  327. requestSequence += 1; // increment the sequence
  328. var requestNumber = requestSequence, // this request's sequence number
  329. data = options.data, // ajax data function
  330. url = ajaxUrl, // ajax url string or function
  331. transport = options.transport || $.ajax,
  332. type = options.type || 'GET', // set type of request (GET or POST)
  333. params = {};
  334. data = data ? data.call(self, query.term, query.page, query.context) : null;
  335. url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
  336. if( null !== handler) { handler.abort(); }
  337. if (options.params) {
  338. if ($.isFunction(options.params)) {
  339. $.extend(params, options.params.call(self));
  340. } else {
  341. $.extend(params, options.params);
  342. }
  343. }
  344. $.extend(params, {
  345. url: url,
  346. dataType: options.dataType,
  347. data: data,
  348. type: type,
  349. cache: false,
  350. success: function (data) {
  351. if (requestNumber < requestSequence) {
  352. return;
  353. }
  354. // TODO - replace query.page with query so users have access to term, page, etc.
  355. var results = options.results(data, query.page);
  356. query.callback(results);
  357. }
  358. });
  359. handler = transport.call(self, params);
  360. }, quietMillis);
  361. };
  362. }
  363. /**
  364. * Produces a query function that works with a local array
  365. *
  366. * @param options object containing configuration parameters. The options parameter can either be an array or an
  367. * object.
  368. *
  369. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  370. *
  371. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  372. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  373. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  374. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  375. * the text.
  376. */
  377. function local(options) {
  378. var data = options, // data elements
  379. dataText,
  380. tmp,
  381. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  382. if ($.isArray(data)) {
  383. tmp = data;
  384. data = { results: tmp };
  385. }
  386. if ($.isFunction(data) === false) {
  387. tmp = data;
  388. data = function() { return tmp; };
  389. }
  390. var dataItem = data();
  391. if (dataItem.text) {
  392. text = dataItem.text;
  393. // if text is not a function we assume it to be a key name
  394. if (!$.isFunction(text)) {
  395. 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
  396. text = function (item) { return item[dataText]; };
  397. }
  398. }
  399. return function (query) {
  400. var t = query.term, filtered = { results: [] }, process;
  401. if (t === "") {
  402. query.callback(data());
  403. return;
  404. }
  405. process = function(datum, collection) {
  406. var group, attr;
  407. datum = datum[0];
  408. if (datum.children) {
  409. group = {};
  410. for (attr in datum) {
  411. if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
  412. }
  413. group.children=[];
  414. $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
  415. if (group.children.length || query.matcher(t, text(group), datum)) {
  416. collection.push(group);
  417. }
  418. } else {
  419. if (query.matcher(t, text(datum), datum)) {
  420. collection.push(datum);
  421. }
  422. }
  423. };
  424. $(data().results).each2(function(i, datum) { process(datum, filtered.results); });
  425. query.callback(filtered);
  426. };
  427. }
  428. // TODO javadoc
  429. function tags(data) {
  430. var isFunc = $.isFunction(data);
  431. return function (query) {
  432. var t = query.term, filtered = {results: []};
  433. $(isFunc ? data() : data).each(function () {
  434. var isObject = this.text !== undefined,
  435. text = isObject ? this.text : this;
  436. if (t === "" || query.matcher(t, text)) {
  437. filtered.results.push(isObject ? this : {id: this, text: this});
  438. }
  439. });
  440. query.callback(filtered);
  441. };
  442. }
  443. /**
  444. * Checks if the formatter function should be used.
  445. *
  446. * Throws an error if it is not a function. Returns true if it should be used,
  447. * false if no formatting should be performed.
  448. *
  449. * @param formatter
  450. */
  451. function checkFormatter(formatter, formatterName) {
  452. if ($.isFunction(formatter)) return true;
  453. if (!formatter) return false;
  454. throw new Error("formatterName must be a function or a falsy value");
  455. }
  456. function evaluate(val) {
  457. return $.isFunction(val) ? val() : val;
  458. }
  459. function countResults(results) {
  460. var count = 0;
  461. $.each(results, function(i, item) {
  462. if (item.children) {
  463. count += countResults(item.children);
  464. } else {
  465. count++;
  466. }
  467. });
  468. return count;
  469. }
  470. /**
  471. * Default tokenizer. This function uses breaks the input on substring match of any string from the
  472. * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
  473. * two options have to be defined in order for the tokenizer to work.
  474. *
  475. * @param input text user has typed so far or pasted into the search field
  476. * @param selection currently selected choices
  477. * @param selectCallback function(choice) callback tho add the choice to selection
  478. * @param opts select2's opts
  479. * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
  480. */
  481. function defaultTokenizer(input, selection, selectCallback, opts) {
  482. var original = input, // store the original so we can compare and know if we need to tell the search to update its text
  483. dupe = false, // check for whether a token we extracted represents a duplicate selected choice
  484. token, // token
  485. index, // position at which the separator was found
  486. i, l, // looping variables
  487. separator; // the matched separator
  488. if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
  489. while (true) {
  490. index = -1;
  491. for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
  492. separator = opts.tokenSeparators[i];
  493. index = input.indexOf(separator);
  494. if (index >= 0) break;
  495. }
  496. if (index < 0) break; // did not find any token separator in the input string, bail
  497. token = input.substring(0, index);
  498. input = input.substring(index + separator.length);
  499. if (token.length > 0) {
  500. token = opts.createSearchChoice(token, selection);
  501. if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
  502. dupe = false;
  503. for (i = 0, l = selection.length; i < l; i++) {
  504. if (equal(opts.id(token), opts.id(selection[i]))) {
  505. dupe = true; break;
  506. }
  507. }
  508. if (!dupe) selectCallback(token);
  509. }
  510. }
  511. }
  512. if (original!==input) return input;
  513. }
  514. /**
  515. * Creates a new class
  516. *
  517. * @param superClass
  518. * @param methods
  519. */
  520. function clazz(SuperClass, methods) {
  521. var constructor = function () {};
  522. constructor.prototype = new SuperClass;
  523. constructor.prototype.constructor = constructor;
  524. constructor.prototype.parent = SuperClass.prototype;
  525. constructor.prototype = $.extend(constructor.prototype, methods);
  526. return constructor;
  527. }
  528. AbstractSelect2 = clazz(Object, {
  529. // abstract
  530. bind: function (func) {
  531. var self = this;
  532. return function () {
  533. func.apply(self, arguments);
  534. };
  535. },
  536. // abstract
  537. init: function (opts) {
  538. var results, search, resultsSelector = ".select2-results", mask;
  539. // prepare options
  540. this.opts = opts = this.prepareOpts(opts);
  541. this.id=opts.id;
  542. // destroy if called on an existing component
  543. if (opts.element.data("select2") !== undefined &&
  544. opts.element.data("select2") !== null) {
  545. this.destroy();
  546. }
  547. this.enabled=true;
  548. this.container = this.createContainer();
  549. this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
  550. this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
  551. this.container.attr("id", this.containerId);
  552. // cache the body so future lookups are cheap
  553. this.body = thunk(function() { return opts.element.closest("body"); });
  554. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  555. this.container.css(evaluate(opts.containerCss));
  556. this.container.addClass(evaluate(opts.containerCssClass));
  557. this.elementTabIndex = this.opts.element.attr("tabIndex");
  558. // swap container for the element
  559. this.opts.element
  560. .data("select2", this)
  561. .addClass("select2-offscreen")
  562. .bind("focus.select2", function() { $(this).select2("focus"); })
  563. .attr("tabIndex", "-1")
  564. .before(this.container);
  565. this.container.data("select2", this);
  566. this.dropdown = this.container.find(".select2-drop");
  567. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  568. this.dropdown.data("select2", this);
  569. this.results = results = this.container.find(resultsSelector);
  570. this.search = search = this.container.find("input.select2-input");
  571. search.attr("tabIndex", this.elementTabIndex);
  572. this.resultsPage = 0;
  573. this.context = null;
  574. // initialize the container
  575. this.initContainer();
  576. installFilteredMouseMove(this.results);
  577. this.dropdown.delegate(resultsSelector, "mousemove-filtered touchstart touchmove touchend", this.bind(this.highlightUnderEvent));
  578. installDebouncedScroll(80, this.results);
  579. this.dropdown.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  580. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  581. if ($.fn.mousewheel) {
  582. results.mousewheel(function (e, delta, deltaX, deltaY) {
  583. var top = results.scrollTop(), height;
  584. if (deltaY > 0 && top - deltaY <= 0) {
  585. results.scrollTop(0);
  586. killEvent(e);
  587. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  588. results.scrollTop(results.get(0).scrollHeight - results.height());
  589. killEvent(e);
  590. }
  591. });
  592. }
  593. installKeyUpChangeEvent(search);
  594. search.bind("keyup-change input paste", this.bind(this.updateResults));
  595. search.bind("focus", function () { search.addClass("select2-focused"); });
  596. search.bind("blur", function () { search.removeClass("select2-focused");});
  597. this.dropdown.delegate(resultsSelector, "mouseup", this.bind(function (e) {
  598. if ($(e.target).closest(".select2-result-selectable").length > 0) {
  599. this.highlightUnderEvent(e);
  600. this.selectHighlighted(e);
  601. }
  602. }));
  603. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  604. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  605. // dom it will trigger the popup close, which is not what we want
  606. this.dropdown.bind("click mouseup mousedown", function (e) { e.stopPropagation(); });
  607. if ($.isFunction(this.opts.initSelection)) {
  608. // initialize selection based on the current value of the source element
  609. this.initSelection();
  610. // if the user has provided a function that can set selection based on the value of the source element
  611. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  612. this.monitorSource();
  613. }
  614. if (opts.element.is(":disabled") || opts.element.is("[readonly='readonly']")) this.disable();
  615. // Calculate size of scrollbar
  616. scrollBarDimensions = scrollBarDimensions || measureScrollbar();
  617. },
  618. // abstract
  619. destroy: function () {
  620. var select2 = this.opts.element.data("select2");
  621. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  622. if (select2 !== undefined) {
  623. select2.container.remove();
  624. select2.dropdown.remove();
  625. select2.opts.element
  626. .removeClass("select2-offscreen")
  627. .removeData("select2")
  628. .unbind(".select2")
  629. .attr({"tabIndex": this.elementTabIndex})
  630. .show();
  631. }
  632. },
  633. // abstract
  634. prepareOpts: function (opts) {
  635. var element, select, idKey, ajaxUrl;
  636. element = opts.element;
  637. if (element.get(0).tagName.toLowerCase() === "select") {
  638. this.select = select = opts.element;
  639. }
  640. if (select) {
  641. // these options are not allowed when attached to a select because they are picked up off the element itself
  642. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  643. if (this in opts) {
  644. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  645. }
  646. });
  647. }
  648. opts = $.extend({}, {
  649. populateResults: function(container, results, query) {
  650. var populate, data, result, children, id=this.opts.id, self=this;
  651. populate=function(results, container, depth) {
  652. var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
  653. results = opts.sortResults(results, container, query);
  654. for (i = 0, l = results.length; i < l; i = i + 1) {
  655. result=results[i];
  656. disabled = (result.disabled === true);
  657. selectable = (!disabled) && (id(result) !== undefined);
  658. compound=result.children && result.children.length > 0;
  659. node=$("<li></li>");
  660. node.addClass("select2-results-dept-"+depth);
  661. node.addClass("select2-result");
  662. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  663. if (disabled) { node.addClass("select2-disabled"); }
  664. if (compound) { node.addClass("select2-result-with-children"); }
  665. node.addClass(self.opts.formatResultCssClass(result));
  666. label=$(document.createElement("div"));
  667. label.addClass("select2-result-label");
  668. formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
  669. if (formatted!==undefined) {
  670. label.html(formatted);
  671. }
  672. node.append(label);
  673. if (compound) {
  674. innerContainer=$("<ul></ul>");
  675. innerContainer.addClass("select2-result-sub");
  676. populate(result.children, innerContainer, depth+1);
  677. node.append(innerContainer);
  678. }
  679. node.data("select2-data", result);
  680. container.append(node);
  681. }
  682. };
  683. populate(results, container, 0);
  684. }
  685. }, $.fn.select2.defaults, opts);
  686. if (typeof(opts.id) !== "function") {
  687. idKey = opts.id;
  688. opts.id = function (e) { return e[idKey]; };
  689. }
  690. if ($.isArray(opts.element.data("select2Tags"))) {
  691. if ("tags" in opts) {
  692. throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
  693. }
  694. opts.tags=opts.element.data("select2Tags");
  695. }
  696. if (select) {
  697. opts.query = this.bind(function (query) {
  698. var data = { results: [], more: false },
  699. term = query.term,
  700. children, firstChild, process;
  701. process=function(element, collection) {
  702. var group;
  703. if (element.is("option")) {
  704. if (query.matcher(term, element.text(), element)) {
  705. collection.push({id:element.attr("value"), text:element.text(), element: element.get(), css: element.attr("class"), disabled: equal(element.attr("disabled"), "disabled") });
  706. }
  707. } else if (element.is("optgroup")) {
  708. group={text:element.attr("label"), children:[], element: element.get(), css: element.attr("class")};
  709. element.children().each2(function(i, elm) { process(elm, group.children); });
  710. if (group.children.length>0) {
  711. collection.push(group);
  712. }
  713. }
  714. };
  715. children=element.children();
  716. // ignore the placeholder option if there is one
  717. if (this.getPlaceholder() !== undefined && children.length > 0) {
  718. firstChild = children[0];
  719. if ($(firstChild).text() === "") {
  720. children=children.not(firstChild);
  721. }
  722. }
  723. children.each2(function(i, elm) { process(elm, data.results); });
  724. query.callback(data);
  725. });
  726. // this is needed because inside val() we construct choices from options and there id is hardcoded
  727. opts.id=function(e) { return e.id; };
  728. opts.formatResultCssClass = function(data) { return data.css; };
  729. } else {
  730. if (!("query" in opts)) {
  731. if ("ajax" in opts) {
  732. ajaxUrl = opts.element.data("ajax-url");
  733. if (ajaxUrl && ajaxUrl.length > 0) {
  734. opts.ajax.url = ajaxUrl;
  735. }
  736. opts.query = ajax.call(opts.element, opts.ajax);
  737. } else if ("data" in opts) {
  738. opts.query = local(opts.data);
  739. } else if ("tags" in opts) {
  740. opts.query = tags(opts.tags);
  741. if (opts.createSearchChoice === undefined) {
  742. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  743. }
  744. if (opts.initSelection === undefined) {
  745. opts.initSelection = function (element, callback) {
  746. var data = [];
  747. $(splitVal(element.val(), opts.separator)).each(function () {
  748. var id = this, text = this, tags=opts.tags;
  749. if ($.isFunction(tags)) tags=tags();
  750. $(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } });
  751. data.push({id: id, text: text});
  752. });
  753. callback(data);
  754. };
  755. }
  756. }
  757. }
  758. }
  759. if (typeof(opts.query) !== "function") {
  760. throw "query function not defined for Select2 " + opts.element.attr("id");
  761. }
  762. return opts;
  763. },
  764. /**
  765. * Monitor the original element for changes and update select2 accordingly
  766. */
  767. // abstract
  768. monitorSource: function () {
  769. var el = this.opts.element, sync;
  770. el.bind("change.select2", this.bind(function (e) {
  771. if (this.opts.element.data("select2-change-triggered") !== true) {
  772. this.initSelection();
  773. }
  774. }));
  775. sync = this.bind(function () {
  776. var enabled, readonly, self = this;
  777. // sync enabled state
  778. enabled = this.opts.element.attr("disabled") !== "disabled";
  779. readonly = this.opts.element.attr("readonly") === "readonly";
  780. enabled = enabled && !readonly;
  781. if (this.enabled !== enabled) {
  782. if (enabled) {
  783. this.enable();
  784. } else {
  785. this.disable();
  786. }
  787. }
  788. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  789. this.container.addClass(evaluate(this.opts.containerCssClass));
  790. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  791. this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
  792. });
  793. // mozilla and IE
  794. el.bind("propertychange.select2 DOMAttrModified.select2", sync);
  795. // safari and chrome
  796. if (typeof WebKitMutationObserver !== "undefined") {
  797. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  798. this.propertyObserver = new WebKitMutationObserver(function (mutations) {
  799. mutations.forEach(sync);
  800. });
  801. this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
  802. }
  803. },
  804. /**
  805. * Triggers the change event on the source element
  806. */
  807. // abstract
  808. triggerChange: function (details) {
  809. details = details || {};
  810. details= $.extend({}, details, { type: "change", val: this.val() });
  811. // prevents recursive triggering
  812. this.opts.element.data("select2-change-triggered", true);
  813. this.opts.element.trigger(details);
  814. this.opts.element.data("select2-change-triggered", false);
  815. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  816. // so here we trigger the click event manually
  817. this.opts.element.click();
  818. // ValidationEngine ignorea the change event and listens instead to blur
  819. // so here we trigger the blur event manually if so desired
  820. if (this.opts.blurOnChange)
  821. this.opts.element.blur();
  822. },
  823. // abstract
  824. enable: function() {
  825. if (this.enabled) return;
  826. this.enabled=true;
  827. this.container.removeClass("select2-container-disabled");
  828. this.opts.element.removeAttr("disabled");
  829. },
  830. // abstract
  831. disable: function() {
  832. if (!this.enabled) return;
  833. this.close();
  834. this.enabled=false;
  835. this.container.addClass("select2-container-disabled");
  836. this.opts.element.attr("disabled", "disabled");
  837. },
  838. // abstract
  839. opened: function () {
  840. return this.container.hasClass("select2-dropdown-open");
  841. },
  842. // abstract
  843. positionDropdown: function() {
  844. var $dropdown = this.dropdown,
  845. offset = this.container.offset(),
  846. height = this.container.outerHeight(false),
  847. width = this.container.outerWidth(false),
  848. dropHeight = $dropdown.outerHeight(false),
  849. viewPortRight = $(window).scrollLeft() + $(window).width(),
  850. viewportBottom = $(window).scrollTop() + $(window).height(),
  851. dropTop = offset.top + height,
  852. dropLeft = offset.left,
  853. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  854. enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
  855. dropWidth = $dropdown.outerWidth(false),
  856. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
  857. aboveNow = $dropdown.hasClass("select2-drop-above"),
  858. bodyOffset,
  859. above,
  860. css,
  861. resultsListNode;
  862. if (this.opts.dropdownAutoWidth) {
  863. resultsListNode = $('.select2-results', $dropdown)[0];
  864. $dropdown.addClass('select2-drop-auto-width');
  865. $dropdown.css('width', '');
  866. // Add scrollbar width to dropdown if vertical scrollbar is present
  867. dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
  868. dropWidth > width ? width = dropWidth : dropWidth = width;
  869. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
  870. }
  871. else {
  872. this.container.removeClass('select2-drop-auto-width');
  873. }
  874. //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  875. //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  876. // fix positioning when body has an offset and is not position: static
  877. if (this.body().css('position') !== 'static') {
  878. bodyOffset = this.body().offset();
  879. dropTop -= bodyOffset.top;
  880. dropLeft -= bodyOffset.left;
  881. }
  882. // always prefer the current above/below alignment, unless there is not enough room
  883. if (aboveNow) {
  884. above = true;
  885. if (!enoughRoomAbove && enoughRoomBelow) above = false;
  886. } else {
  887. above = false;
  888. if (!enoughRoomBelow && enoughRoomAbove) above = true;
  889. }
  890. if (!enoughRoomOnRight) {
  891. dropLeft = offset.left + width - dropWidth;
  892. }
  893. if (above) {
  894. dropTop = offset.top - dropHeight;
  895. this.container.addClass("select2-drop-above");
  896. $dropdown.addClass("select2-drop-above");
  897. }
  898. else {
  899. this.container.removeClass("select2-drop-above");
  900. $dropdown.removeClass("select2-drop-above");
  901. }
  902. css = $.extend({
  903. top: dropTop,
  904. left: dropLeft,
  905. width: width
  906. }, evaluate(this.opts.dropdownCss));
  907. $dropdown.css(css);
  908. },
  909. // abstract
  910. shouldOpen: function() {
  911. var event;
  912. if (this.opened()) return false;
  913. event = $.Event("opening");
  914. this.opts.element.trigger(event);
  915. return !event.isDefaultPrevented();
  916. },
  917. // abstract
  918. clearDropdownAlignmentPreference: function() {
  919. // clear the classes used to figure out the preference of where the dropdown should be opened
  920. this.container.removeClass("select2-drop-above");
  921. this.dropdown.removeClass("select2-drop-above");
  922. },
  923. /**
  924. * Opens the dropdown
  925. *
  926. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  927. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  928. */
  929. // abstract
  930. open: function () {
  931. if (!this.shouldOpen()) return false;
  932. window.setTimeout(this.bind(this.opening), 1);
  933. return true;
  934. },
  935. /**
  936. * Performs the opening of the dropdown
  937. */
  938. // abstract
  939. opening: function() {
  940. var cid = this.containerId,
  941. scroll = "scroll." + cid,
  942. resize = "resize."+cid,
  943. orient = "orientationchange."+cid,
  944. mask;
  945. this.clearDropdownAlignmentPreference();
  946. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  947. if(this.dropdown[0] !== this.body().children().last()[0]) {
  948. this.dropdown.detach().appendTo(this.body());
  949. }
  950. this.updateResults(true);
  951. // create the dropdown mask if doesnt already exist
  952. mask = $("#select2-drop-mask");
  953. if (mask.length == 0) {
  954. mask = $(document.createElement("div"));
  955. mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
  956. mask.hide();
  957. mask.appendTo(this.body());
  958. mask.bind("mousedown touchstart", function (e) {
  959. var dropdown = $("#select2-drop"), self;
  960. if (dropdown.length > 0) {
  961. self=dropdown.data("select2");
  962. if (self.opts.selectOnBlur) {
  963. self.selectHighlighted({noFocus: true});
  964. }
  965. self.close();
  966. }
  967. });
  968. }
  969. // ensure the mask is always right before the dropdown
  970. if (this.dropdown.prev()[0] !== mask[0]) {
  971. this.dropdown.before(mask);
  972. }
  973. // move the global id to the correct dropdown
  974. $("#select2-drop").removeAttr("id");
  975. this.dropdown.attr("id", "select2-drop");
  976. // show the elements
  977. mask.css(_makeMaskCss());
  978. mask.show();
  979. this.dropdown.show();
  980. this.positionDropdown();
  981. this.dropdown.addClass("select2-drop-active");
  982. this.ensureHighlightVisible();
  983. // attach listeners to events that can change the position of the container and thus require
  984. // the position of the dropdown to be updated as well so it does not come unglued from the container
  985. var that = this;
  986. this.container.parents().add(window).each(function () {
  987. $(this).bind(resize+" "+scroll+" "+orient, function (e) {
  988. $("#select2-drop-mask").css(_makeMaskCss());
  989. that.positionDropdown();
  990. });
  991. });
  992. this.focusSearch();
  993. function _makeMaskCss() {
  994. return {
  995. width : Math.max(document.documentElement.scrollWidth, $(window).width()),
  996. height : Math.max(document.documentElement.scrollHeight, $(window).height())
  997. }
  998. }
  999. },
  1000. // abstract
  1001. close: function () {
  1002. if (!this.opened()) return;
  1003. var cid = this.containerId,
  1004. scroll = "scroll." + cid,
  1005. resize = "resize."+cid,
  1006. orient = "orientationchange."+cid;
  1007. // unbind event listeners
  1008. this.container.parents().add(window).each(function () { $(this).unbind(scroll).unbind(resize).unbind(orient); });
  1009. this.clearDropdownAlignmentPreference();
  1010. $("#select2-drop-mask").hide();
  1011. this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
  1012. this.dropdown.hide();
  1013. this.container.removeClass("select2-dropdown-open");
  1014. this.results.empty();
  1015. this.clearSearch();
  1016. this.search.removeClass("select2-active");
  1017. this.opts.element.trigger($.Event("close"));
  1018. },
  1019. // abstract
  1020. clearSearch: function () {
  1021. },
  1022. //abstract
  1023. getMaximumSelectionSize: function() {
  1024. return evaluate(this.opts.maximumSelectionSize);
  1025. },
  1026. // abstract
  1027. ensureHighlightVisible: function () {
  1028. var results = this.results, children, index, child, hb, rb, y, more;
  1029. index = this.highlight();
  1030. if (index < 0) return;
  1031. if (index == 0) {
  1032. // if the first element is highlighted scroll all the way to the top,
  1033. // that way any unselectable headers above it will also be scrolled
  1034. // into view
  1035. results.scrollTop(0);
  1036. return;
  1037. }
  1038. children = this.findHighlightableChoices().find('.select2-result-label');
  1039. child = $(children[index]);
  1040. hb = child.offset().top + child.outerHeight(true);
  1041. // if this is the last child lets also make sure select2-more-results is visible
  1042. if (index === children.length - 1) {
  1043. more = results.find("li.select2-more-results");
  1044. if (more.length > 0) {
  1045. hb = more.offset().top + more.outerHeight(true);
  1046. }
  1047. }
  1048. rb = results.offset().top + results.outerHeight(true);
  1049. if (hb > rb) {
  1050. results.scrollTop(results.scrollTop() + (hb - rb));
  1051. }
  1052. y = child.offset().top - results.offset().top;
  1053. // make sure the top of the element is visible
  1054. if (y < 0 && child.css('display') != 'none' ) {
  1055. results.scrollTop(results.scrollTop() + y); // y is negative
  1056. }
  1057. },
  1058. // abstract
  1059. findHighlightableChoices: function() {
  1060. return this.results.find(".select2-result-selectable:not(.select2-selected):not(.select2-disabled)");
  1061. },
  1062. // abstract
  1063. moveHighlight: function (delta) {
  1064. var choices = this.findHighlightableChoices(),
  1065. index = this.highlight();
  1066. while (index > -1 && index < choices.length) {
  1067. index += delta;
  1068. var choice = $(choices[index]);
  1069. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
  1070. this.highlight(index);
  1071. break;
  1072. }
  1073. }
  1074. },
  1075. // abstract
  1076. highlight: function (index) {
  1077. var choices = this.findHighlightableChoices(),
  1078. choice,
  1079. data;
  1080. if (arguments.length === 0) {
  1081. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  1082. }
  1083. if (index >= choices.length) index = choices.length - 1;
  1084. if (index < 0) index = 0;
  1085. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1086. choice = $(choices[index]);
  1087. choice.addClass("select2-highlighted");
  1088. this.ensureHighlightVisible();
  1089. data = choice.data("select2-data");
  1090. if (data) {
  1091. this.opts.element.trigger({ type: "highlight", val: this.id(data), choice: data });
  1092. }
  1093. },
  1094. // abstract
  1095. countSelectableResults: function() {
  1096. return this.findHighlightableChoices().length;
  1097. },
  1098. // abstract
  1099. highlightUnderEvent: function (event) {
  1100. var el = $(event.target).closest(".select2-result-selectable");
  1101. if (el.length > 0 && !el.is(".select2-highlighted")) {
  1102. var choices = this.findHighlightableChoices();
  1103. this.highlight(choices.index(el));
  1104. } else if (el.length == 0) {
  1105. // if we are over an unselectable item remove al highlights
  1106. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1107. }
  1108. },
  1109. // abstract
  1110. loadMoreIfNeeded: function () {
  1111. var results = this.results,
  1112. more = results.find("li.select2-more-results"),
  1113. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  1114. offset = -1, // index of first element without data
  1115. page = this.resultsPage + 1,
  1116. self=this,
  1117. term=this.search.val(),
  1118. context=this.context;
  1119. if (more.length === 0) return;
  1120. below = more.offset().top - results.offset().top - results.height();
  1121. if (below <= this.opts.loadMorePadding) {
  1122. more.addClass("select2-active");
  1123. this.opts.query({
  1124. element: this.opts.element,
  1125. term: term,
  1126. page: page,
  1127. context: context,
  1128. matcher: this.opts.matcher,
  1129. callback: this.bind(function (data) {
  1130. // ignore a response if the select2 has been closed before it was received
  1131. if (!self.opened()) return;
  1132. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  1133. self.postprocessResults(data, false, false);
  1134. if (data.more===true) {
  1135. more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
  1136. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1137. } else {
  1138. more.remove();
  1139. }
  1140. self.positionDropdown();
  1141. self.resultsPage = page;
  1142. self.context = data.context;
  1143. })});
  1144. }
  1145. },
  1146. /**
  1147. * Default tokenizer function which does nothing
  1148. */
  1149. tokenize: function() {
  1150. },
  1151. /**
  1152. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  1153. */
  1154. // abstract
  1155. updateResults: function (initial) {
  1156. var search = this.search,
  1157. results = this.results,
  1158. opts = this.opts,
  1159. data,
  1160. self = this,
  1161. input,
  1162. term = search.val(),
  1163. lastTerm=$.data(this.container, "select2-last-term");
  1164. // prevent duplicate queries against the same term
  1165. if (initial !== true && lastTerm && equal(term, lastTerm)) return;
  1166. $.data(this.container, "select2-last-term", term);
  1167. // if the search is currently hidden we do not alter the results
  1168. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  1169. return;
  1170. }
  1171. function postRender() {
  1172. results.scrollTop(0);
  1173. search.removeClass("select2-active");
  1174. self.positionDropdown();
  1175. }
  1176. function render(html) {
  1177. results.html(html);
  1178. postRender();
  1179. }
  1180. var maxSelSize = this.getMaximumSelectionSize();
  1181. if (maxSelSize >=1) {
  1182. data = this.data();
  1183. if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  1184. render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>");
  1185. return;
  1186. }
  1187. }
  1188. if (search.val().length < opts.minimumInputLength) {
  1189. if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  1190. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  1191. } else {
  1192. render("");
  1193. }
  1194. return;
  1195. }
  1196. if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
  1197. if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
  1198. render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>");
  1199. } else {
  1200. render("");
  1201. }
  1202. return;
  1203. }
  1204. if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
  1205. render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
  1206. }
  1207. search.addClass("select2-active");
  1208. // give the tokenizer a chance to pre-process the input
  1209. input = this.tokenize();
  1210. if (input != undefined && input != null) {
  1211. search.val(input);
  1212. }
  1213. this.resultsPage = 1;
  1214. opts.query({
  1215. element: opts.element,
  1216. term: search.val(),
  1217. page: this.resultsPage,
  1218. context: null,
  1219. matcher: opts.matcher,
  1220. callback: this.bind(function (data) {
  1221. var def; // default choice
  1222. // ignore a response if the select2 has been closed before it was received
  1223. if (!this.opened()) {
  1224. this.search.removeClass("select2-active");
  1225. return;
  1226. }
  1227. // save context, if any
  1228. this.context = (data.context===undefined) ? null : data.context;
  1229. // create a default choice and prepend it to the list
  1230. if (this.opts.createSearchChoice && search.val() !== "") {
  1231. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  1232. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  1233. if ($(data.results).filter(
  1234. function () {
  1235. return equal(self.id(this), self.id(def));
  1236. }).length === 0) {
  1237. data.results.unshift(def);
  1238. }
  1239. }
  1240. }
  1241. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  1242. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  1243. return;
  1244. }
  1245. results.empty();
  1246. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  1247. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  1248. results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
  1249. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1250. }
  1251. this.postprocessResults(data, initial);
  1252. postRender();
  1253. this.opts.element.trigger({ type: "loaded", data:data });
  1254. })});
  1255. },
  1256. // abstract
  1257. cancel: function () {
  1258. this.close();
  1259. },
  1260. // abstract
  1261. blur: function () {
  1262. // if selectOnBlur == true, select the currently highlighted option
  1263. if (this.opts.selectOnBlur)
  1264. this.selectHighlighted({noFocus: true});
  1265. this.close();
  1266. this.container.removeClass("select2-container-active");
  1267. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  1268. if (this.search[0] === document.activeElement) { this.search.blur(); }
  1269. this.clearSearch();
  1270. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1271. },
  1272. // abstract
  1273. focusSearch: function () {
  1274. focus(this.search);
  1275. },
  1276. // abstract
  1277. selectHighlighted: function (options) {
  1278. var index=this.highlight(),
  1279. highlighted=this.results.find(".select2-highlighted"),
  1280. data = highlighted.closest('.select2-result').data("select2-data");
  1281. if (data) {
  1282. this.highlight(index);
  1283. this.onSelect(data, options);
  1284. }
  1285. },
  1286. // abstract
  1287. getPlaceholder: function () {
  1288. return this.opts.element.attr("placeholder") ||
  1289. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1290. this.opts.element.data("placeholder") ||
  1291. this.opts.placeholder;
  1292. },
  1293. /**
  1294. * Get the desired width for the container element. This is
  1295. * derived first from option `width` passed to select2, then
  1296. * the inline 'style' on the original element, and finally
  1297. * falls back to the jQuery calculated element width.
  1298. */
  1299. // abstract
  1300. initContainerWidth: function () {
  1301. function resolveContainerWidth() {
  1302. var style, attrs, matches, i, l;
  1303. if (this.opts.width === "off") {
  1304. return null;
  1305. } else if (this.opts.width === "element"){
  1306. return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
  1307. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1308. // check if there is inline style on the element that contains width
  1309. style = this.opts.element.attr('style');
  1310. if (style !== undefined) {
  1311. attrs = style.split(';');
  1312. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1313. matches = attrs[i].replace(/\s/g, '')
  1314. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  1315. if (matches !== null && matches.length >= 1)
  1316. return matches[1];
  1317. }
  1318. }
  1319. if (this.opts.width === "resolve") {
  1320. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1321. // when attached to input type=hidden or elements hidden via css
  1322. style = this.opts.element.css('width');
  1323. if (style.indexOf("%") > 0) return style;
  1324. // finally, fallback on the calculated width of the element
  1325. return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
  1326. }
  1327. return null;
  1328. } else if ($.isFunction(this.opts.width)) {
  1329. return this.opts.width();
  1330. } else {
  1331. return this.opts.width;
  1332. }
  1333. };
  1334. var width = resolveContainerWidth.call(this);
  1335. if (width !== null) {
  1336. this.container.css("width", width);
  1337. }
  1338. }
  1339. });
  1340. SingleSelect2 = clazz(AbstractSelect2, {
  1341. // single
  1342. createContainer: function () {
  1343. var container = $(document.createElement("div")).attr({
  1344. "class": "select2-container"
  1345. }).html([
  1346. "<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>",
  1347. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  1348. " <div><b></b></div>" ,
  1349. "</a>",
  1350. "<input class='select2-focusser select2-offscreen' type='text'/>",
  1351. "<div class='select2-drop' style='display:none'>" ,
  1352. " <div class='select2-search'>" ,
  1353. " <input type='text' autocomplete='off' class='select2-input'/>" ,
  1354. " </div>" ,
  1355. " <ul class='select2-results'>" ,
  1356. " </ul>" ,
  1357. "</div>"].join(""));
  1358. return container;
  1359. },
  1360. // single
  1361. disable: function() {
  1362. if (!this.enabled) return;
  1363. this.parent.disable.apply(this, arguments);
  1364. this.focusser.attr("disabled", "disabled");
  1365. },
  1366. // single
  1367. enable: function() {
  1368. if (this.enabled) return;
  1369. this.parent.enable.apply(this, arguments);
  1370. this.focusser.removeAttr("disabled");
  1371. },
  1372. // single
  1373. opening: function () {
  1374. this.parent.opening.apply(this, arguments);
  1375. this.focusser.attr("disabled", "disabled");
  1376. this.opts.element.trigger($.Event("open"));
  1377. },
  1378. // single
  1379. close: function () {
  1380. if (!this.opened()) return;
  1381. this.parent.close.apply(this, arguments);
  1382. this.focusser.removeAttr("disabled");
  1383. focus(this.focusser);
  1384. },
  1385. // single
  1386. focus: function () {
  1387. if (this.opened()) {
  1388. this.close();
  1389. } else {
  1390. this.focusser.removeAttr("disabled");
  1391. this.focusser.focus();
  1392. }
  1393. },
  1394. // single
  1395. isFocused: function () {
  1396. return this.container.hasClass("select2-container-active");
  1397. },
  1398. // single
  1399. cancel: function () {
  1400. this.parent.cancel.apply(this, arguments);
  1401. this.focusser.removeAttr("disabled");
  1402. this.focusser.focus();
  1403. },
  1404. // single
  1405. initContainer: function () {
  1406. var selection,
  1407. container = this.container,
  1408. dropdown = this.dropdown,
  1409. clickingInside = false;
  1410. this.showSearch(this.opts.minimumResultsForSearch >= 0);
  1411. this.selection = selection = container.find(".select2-choice");
  1412. this.focusser = container.find(".select2-focusser");
  1413. // rewrite labels from original element to focusser
  1414. this.focusser.attr("id", "s2id_autogen"+nextUid());
  1415. $("label[for='" + this.opts.element.attr("id") + "']")
  1416. .attr('for', this.focusser.attr('id'));
  1417. this.search.bind("keydown", this.bind(function (e) {
  1418. if (!this.enabled) return;
  1419. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1420. // prevent the page from scrolling
  1421. killEvent(e);
  1422. return;
  1423. }
  1424. switch (e.which) {
  1425. case KEY.UP:
  1426. case KEY.DOWN:
  1427. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1428. killEvent(e);
  1429. return;
  1430. case KEY.TAB:
  1431. case KEY.ENTER:
  1432. this.selectHighlighted();
  1433. killEvent(e);
  1434. return;
  1435. case KEY.ESC:
  1436. this.cancel(e);
  1437. killEvent(e);
  1438. return;
  1439. }
  1440. }));
  1441. this.search.bind("blur", this.bind(function(e) {
  1442. // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
  1443. // without this the search field loses focus which is annoying
  1444. if (document.activeElement === this.body().get(0)) {
  1445. window.setTimeout(this.bind(function() {
  1446. this.search.focus();
  1447. }), 0);
  1448. }
  1449. }));
  1450. this.focusser.bind("keydown", this.bind(function (e) {
  1451. if (!this.enabled) return;
  1452. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1453. return;
  1454. }
  1455. if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
  1456. killEvent(e);
  1457. return;
  1458. }
  1459. if (e.which == KEY.DOWN || e.which == KEY.UP
  1460. || (e.which == KEY.ENTER && this.opts.openOnEnter)) {
  1461. this.open();
  1462. killEvent(e);
  1463. return;
  1464. }
  1465. if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
  1466. if (this.opts.allowClear) {
  1467. this.clear();
  1468. }
  1469. killEvent(e);
  1470. return;
  1471. }
  1472. }));
  1473. installKeyUpChangeEvent(this.focusser);
  1474. this.focusser.bind("keyup-change input", this.bind(function(e) {
  1475. if (this.opened()) return;
  1476. this.open();
  1477. if (this.showSearchInput !== false) {
  1478. this.search.val(this.focusser.val());
  1479. }
  1480. this.focusser.val("");
  1481. killEvent(e);
  1482. }));
  1483. selection.delegate("abbr", "mousedown", this.bind(function (e) {
  1484. if (!this.enabled) return;
  1485. this.clear();
  1486. killEventImmediately(e);
  1487. this.close();
  1488. this.selection.focus();
  1489. }));
  1490. selection.bind("mousedown", this.bind(function (e) {
  1491. clickingInside = true;
  1492. if (this.opened()) {
  1493. this.close();
  1494. } else if (this.enabled) {
  1495. this.open();
  1496. }
  1497. killEvent(e);
  1498. clickingInside = false;
  1499. }));
  1500. dropdown.bind("mousedown", this.bind(function() { this.search.focus(); }));
  1501. selection.bind("focus", this.bind(function(e) {
  1502. killEvent(e);
  1503. }));
  1504. this.focusser.bind("focus", this.bind(function(){
  1505. this.container.addClass("select2-container-active");
  1506. })).bind("blur", this.bind(function() {
  1507. if (!this.opened()) {
  1508. this.container.removeClass("select2-container-active");
  1509. }
  1510. }));
  1511. this.search.bind("focus", this.bind(function(){
  1512. this.container.addClass("select2-container-active");
  1513. }))
  1514. this.initContainerWidth();
  1515. this.setPlaceholder();
  1516. },
  1517. // single
  1518. clear: function(triggerChange) {
  1519. var data=this.selection.data("select2-data");
  1520. if (data) { // guard against queued quick consecutive clicks
  1521. this.opts.element.val("");
  1522. this.selection.find("span").empty();
  1523. this.selection.removeData("select2-data");
  1524. this.setPlaceholder();
  1525. if (triggerChange !== false){
  1526. this.opts.element.trigger({ type: "removed", val: this.id(data), choice: data });
  1527. this.triggerChange({removed:data});
  1528. }
  1529. }
  1530. },
  1531. /**
  1532. * Sets selection based on source element's value
  1533. */
  1534. // single
  1535. initSelection: function () {
  1536. var selected;
  1537. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  1538. this.close();
  1539. this.setPlaceholder();
  1540. } else {
  1541. var self = this;
  1542. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1543. if (selected !== undefined && selected !== null) {
  1544. self.updateSelection(selected);
  1545. self.close();
  1546. self.setPlaceholder();
  1547. }
  1548. });
  1549. }
  1550. },
  1551. // single
  1552. prepareOpts: function () {
  1553. var opts = this.parent.prepareOpts.apply(this, arguments);
  1554. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1555. // install the selection initializer
  1556. opts.initSelection = function (element, callback) {
  1557. var selected = element.find(":selected");
  1558. // a single select box always has a value, no need to null check 'selected'
  1559. if ($.isFunction(callback))
  1560. callback({id: selected.attr("value"), text: selected.text(), element:selected});
  1561. };
  1562. } else if ("data" in opts) {
  1563. // install default initSelection when applied to hidden input and data is local
  1564. opts.initSelection = opts.initSelection || function (element, callback) {
  1565. var id = element.val();
  1566. //search in data by id, storing the actual matching item
  1567. var match = null;
  1568. opts.query({
  1569. matcher: function(term, text, el){
  1570. var is_match = equal(id, opts.id(el));
  1571. if (is_match) {
  1572. match = el;
  1573. }
  1574. return is_match;
  1575. },
  1576. callback: !$.isFunction(callback) ? $.noop : function() {
  1577. callback(match);
  1578. }
  1579. });
  1580. };
  1581. }
  1582. return opts;
  1583. },
  1584. // single
  1585. getPlaceholder: function() {
  1586. // if a placeholder is specified on a single select without the first empty option ignore it
  1587. if (this.select) {
  1588. if (this.select.find("option").first().text() !== "") {
  1589. return undefined;
  1590. }
  1591. }
  1592. return this.parent.getPlaceholder.apply(this, arguments);
  1593. },
  1594. // single
  1595. setPlaceholder: function () {
  1596. var placeholder = this.getPlaceholder();
  1597. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1598. // check for a first blank option if attached to a select
  1599. if (this.select && this.select.find("option:first").text() !== "") return;
  1600. this.selection.find("span").html(this.opts.escapeMarkup(placeholder));
  1601. this.selection.addClass("select2-default");
  1602. this.selection.find("abbr").hide();
  1603. }
  1604. },
  1605. // single
  1606. postprocessResults: function (data, initial, noHighlightUpdate) {
  1607. var selected = 0, self = this, showSearchInput = true;
  1608. // find the selected element in the result list
  1609. this.findHighlightableChoices().each2(function (i, elm) {
  1610. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1611. selected = i;
  1612. return false;
  1613. }
  1614. });
  1615. // and highlight it
  1616. if (noHighlightUpdate !== false) {
  1617. this.highlight(selected);
  1618. }
  1619. // hide the search box if this is the first we got the results and there are a few of them
  1620. if (initial === true) {
  1621. var min=this.opts.minimumResultsForSearch;
  1622. showSearchInput = min < 0 ? false : countResults(data.results) >= min;
  1623. this.showSearch(showSearchInput);
  1624. }
  1625. },
  1626. // single
  1627. showSearch: function(showSearchInput) {
  1628. this.showSearchInput = showSearchInput;
  1629. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1630. //add "select2-with-searchbox" to the container if search box is shown
  1631. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1632. },
  1633. // single
  1634. onSelect: function (data, options) {
  1635. var old = this.opts.element.val();
  1636. this.opts.element.val(this.id(data));
  1637. this.updateSelection(data);
  1638. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  1639. this.close();
  1640. if (!options || !options.noFocus)
  1641. this.selection.focus();
  1642. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1643. },
  1644. // single
  1645. updateSelection: function (data) {
  1646. var container=this.selection.find("span"), formatted;
  1647. this.selection.data("select2-data", data);
  1648. container.empty();
  1649. formatted=this.opts.formatSelection(data, container);
  1650. if (formatted !== undefined) {
  1651. container.append(this.opts.escapeMarkup(formatted));
  1652. }
  1653. this.selection.removeClass("select2-default");
  1654. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1655. this.selection.find("abbr").show();
  1656. }
  1657. },
  1658. // single
  1659. val: function () {
  1660. var val, triggerChange = false, data = null, self = this;
  1661. if (arguments.length === 0) {
  1662. return this.opts.element.val();
  1663. }
  1664. val = arguments[0];
  1665. if (arguments.length > 1) {
  1666. triggerChange = arguments[1];
  1667. }
  1668. if (this.select) {
  1669. this.select
  1670. .val(val)
  1671. .find(":selected").each2(function (i, elm) {
  1672. data = {id: elm.attr("value"), text: elm.text(), element: elm.get(0)};
  1673. return false;
  1674. });
  1675. this.updateSelection(data);
  1676. this.setPlaceholder();
  1677. if (triggerChange) {
  1678. this.triggerChange();
  1679. }
  1680. } else {
  1681. if (this.opts.initSelection === undefined) {
  1682. throw new Error("cannot call val() if initSelection() is not defined");
  1683. }
  1684. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  1685. if (!val && val !== 0) {
  1686. this.clear(triggerChange);
  1687. if (triggerChange) {
  1688. this.triggerChange();
  1689. }
  1690. return;
  1691. }
  1692. this.opts.element.val(val);
  1693. this.opts.initSelection(this.opts.element, function(data){
  1694. self.opts.element.val(!data ? "" : self.id(data));
  1695. self.updateSelection(data);
  1696. self.setPlaceholder();
  1697. if (triggerChange) {
  1698. self.triggerChange();
  1699. }
  1700. });
  1701. }
  1702. },
  1703. // single
  1704. clearSearch: function () {
  1705. this.search.val("");
  1706. this.focusser.val("");
  1707. },
  1708. // single
  1709. data: function(value) {
  1710. var data;
  1711. if (arguments.length === 0) {
  1712. data = this.selection.data("select2-data");
  1713. if (data == undefined) data = null;
  1714. return data;
  1715. } else {
  1716. if (!value || value === "") {
  1717. this.clear();
  1718. } else {
  1719. this.opts.element.val(!value ? "" : this.id(value));
  1720. this.updateSelection(value);
  1721. }
  1722. }
  1723. }
  1724. });
  1725. MultiSelect2 = clazz(AbstractSelect2, {
  1726. // multi
  1727. createContainer: function () {
  1728. var container = $(document.createElement("div")).attr({
  1729. "class": "select2-container select2-container-multi"
  1730. }).html([
  1731. " <ul class='select2-choices'>",
  1732. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1733. " <li class='select2-search-field'>" ,
  1734. " <input type='text' autocomplete='off' class='select2-input'>" ,
  1735. " </li>" ,
  1736. "</ul>" ,
  1737. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1738. " <ul class='select2-results'>" ,
  1739. " </ul>" ,
  1740. "</div>"].join(""));
  1741. return container;
  1742. },
  1743. // multi
  1744. prepareOpts: function () {
  1745. var opts = this.parent.prepareOpts.apply(this, arguments);
  1746. // TODO validate placeholder is a string if specified
  1747. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1748. // install sthe selection initializer
  1749. opts.initSelection = function (element, callback) {
  1750. var data = [];
  1751. element.find(":selected").each2(function (i, elm) {
  1752. data.push({id: elm.attr("value"), text: elm.text(), element: elm[0]});
  1753. });
  1754. callback(data);
  1755. };
  1756. } else if ("data" in opts) {
  1757. // install default initSelection when applied to hidden input and data is local
  1758. opts.initSelection = opts.initSelection || function (element, callback) {
  1759. var ids = splitVal(element.val(), opts.separator);
  1760. //search in data by array of ids, storing matching items in a list
  1761. var matches = [];
  1762. opts.query({
  1763. matcher: function(term, text, el){
  1764. var is_match = $.grep(ids, function(id) {
  1765. return equal(id, opts.id(el));
  1766. }).length;
  1767. if (is_match) {
  1768. matches.push(el);
  1769. }
  1770. return is_match;
  1771. },
  1772. callback: !$.isFunction(callback) ? $.noop : function() {
  1773. callback(matches);
  1774. }
  1775. });
  1776. };
  1777. }
  1778. return opts;
  1779. },
  1780. // multi
  1781. initContainer: function () {
  1782. var selector = ".select2-choices", selection;
  1783. this.searchContainer = this.container.find(".select2-search-field");
  1784. this.selection = selection = this.container.find(selector);
  1785. // rewrite labels from original element to focusser
  1786. this.search.attr("id", "s2id_autogen"+nextUid());
  1787. $("label[for='" + this.opts.element.attr("id") + "']")
  1788. .attr('for', this.search.attr('id'));
  1789. this.search.bind("input paste", this.bind(function() {
  1790. if (!this.enabled) return;
  1791. if (!this.opened()) {
  1792. this.open();
  1793. }
  1794. }));
  1795. this.search.bind("keydown", this.bind(function (e) {
  1796. if (!this.enabled) return;
  1797. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1798. this.close();
  1799. var choices,
  1800. selected = selection.find(".select2-search-choice-focus");
  1801. if (selected.length > 0) {
  1802. this.unselect(selected.first());
  1803. this.search.width(10);
  1804. killEvent(e);
  1805. return;
  1806. }
  1807. choices = selection.find(".select2-search-choice:not(.select2-locked)");
  1808. if (choices.length > 0) {
  1809. choices.last().addClass("select2-search-choice-focus");
  1810. }
  1811. } else {
  1812. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1813. }
  1814. if (this.opened()) {
  1815. switch (e.which) {
  1816. case KEY.UP:
  1817. case KEY.DOWN:
  1818. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1819. killEvent(e);
  1820. return;
  1821. case KEY.ENTER:
  1822. case KEY.TAB:
  1823. this.selectHighlighted();
  1824. killEvent(e);
  1825. return;
  1826. case KEY.ESC:
  1827. this.cancel(e);
  1828. killEvent(e);
  1829. return;
  1830. }
  1831. }
  1832. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  1833. || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1834. return;
  1835. }
  1836. if (e.which === KEY.ENTER) {
  1837. if (this.opts.openOnEnter === false) {
  1838. return;
  1839. } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
  1840. return;
  1841. }
  1842. }
  1843. this.open();
  1844. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1845. // prevent the page from scrolling
  1846. killEvent(e);
  1847. }
  1848. if (e.which === KEY.ENTER) {
  1849. // prevent form from being submitted
  1850. killEvent(e);
  1851. }
  1852. }));
  1853. this.search.bind("keyup", this.bind(this.resizeSearch));
  1854. this.search.bind("blur", this.bind(function(e) {
  1855. this.container.removeClass("select2-container-active");
  1856. this.search.removeClass("select2-focused");
  1857. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1858. if (!this.opened()) this.clearSearch();
  1859. e.stopImmediatePropagation();
  1860. }));
  1861. this.container.delegate(selector, "mousedown", this.bind(function (e) {
  1862. if (!this.enabled) return;
  1863. if ($(e.target).closest(".select2-search-choice").length > 0) {
  1864. // clicked inside a select2 search choice, do not open
  1865. return;
  1866. }
  1867. this.clearPlaceholder();
  1868. this.open();
  1869. this.focusSearch();
  1870. e.preventDefault();
  1871. }));
  1872. this.container.delegate(selector, "focus", this.bind(function () {
  1873. if (!this.enabled) return;
  1874. this.container.addClass("select2-container-active");
  1875. this.dropdown.addClass("select2-drop-active");
  1876. this.clearPlaceholder();
  1877. }));
  1878. this.initContainerWidth();
  1879. // set the placeholder if necessary
  1880. this.clearSearch();
  1881. },
  1882. // multi
  1883. enable: function() {
  1884. if (this.enabled) return;
  1885. this.parent.enable.apply(this, arguments);
  1886. this.search.removeAttr("disabled");
  1887. },
  1888. // multi
  1889. disable: function() {
  1890. if (!this.enabled) return;
  1891. this.parent.disable.apply(this, arguments);
  1892. this.search.attr("disabled", true);
  1893. },
  1894. // multi
  1895. initSelection: function () {
  1896. var data;
  1897. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  1898. this.updateSelection([]);
  1899. this.close();
  1900. // set the placeholder if necessary
  1901. this.clearSearch();
  1902. }
  1903. if (this.select || this.opts.element.val() !== "") {
  1904. var self = this;
  1905. this.opts.initSelection.call(null, this.opts.element, function(data){
  1906. if (data !== undefined && data !== null) {
  1907. self.updateSelection(data);
  1908. self.close();
  1909. // set the placeholder if necessary
  1910. self.clearSearch();
  1911. }
  1912. });
  1913. }
  1914. },
  1915. // multi
  1916. clearSearch: function () {
  1917. var placeholder = this.getPlaceholder();
  1918. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1919. this.search.val(placeholder).addClass("select2-default");
  1920. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1921. // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944
  1922. this.search.width(this.getMaxSearchWidth());
  1923. } else {
  1924. this.search.val("").width(10);
  1925. }
  1926. },
  1927. // multi
  1928. clearPlaceholder: function () {
  1929. if (this.search.hasClass("select2-default")) {
  1930. this.search.val("").removeClass("select2-default");
  1931. }
  1932. },
  1933. // multi
  1934. opening: function () {
  1935. this.clearPlaceholder(); // should be done before super so placeholder is not used to search
  1936. this.resizeSearch();
  1937. this.parent.opening.apply(this, arguments);
  1938. this.focusSearch();
  1939. this.opts.element.trigger($.Event("open"));
  1940. },
  1941. // multi
  1942. close: function () {
  1943. if (!this.opened()) return;
  1944. this.parent.close.apply(this, arguments);
  1945. },
  1946. // multi
  1947. focus: function () {
  1948. this.close();
  1949. this.search.focus();
  1950. //this.opts.element.triggerHandler("focus");
  1951. },
  1952. // multi
  1953. isFocused: function () {
  1954. return this.search.hasClass("select2-focused");
  1955. },
  1956. // multi
  1957. updateSelection: function (data) {
  1958. var ids = [], filtered = [], self = this;
  1959. // filter out duplicates
  1960. $(data).each(function () {
  1961. if (indexOf(self.id(this), ids) < 0) {
  1962. ids.push(self.id(this));
  1963. filtered.push(this);
  1964. }
  1965. });
  1966. data = filtered;
  1967. this.selection.find(".select2-search-choice").remove();
  1968. $(data).each(function () {
  1969. self.addSelectedChoice(this);
  1970. });
  1971. self.postprocessResults();
  1972. },
  1973. // multi
  1974. tokenize: function() {
  1975. var input = this.search.val();
  1976. input = this.opts.tokenizer(input, this.data(), this.bind(this.onSelect), this.opts);
  1977. if (input != null && input != undefined) {
  1978. this.search.val(input);
  1979. if (input.length > 0) {
  1980. this.open();
  1981. }
  1982. }
  1983. },
  1984. // multi
  1985. onSelect: function (data, options) {
  1986. this.addSelectedChoice(data);
  1987. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  1988. if (this.select || !this.opts.closeOnSelect) this.postprocessResults();
  1989. if (this.opts.closeOnSelect) {
  1990. this.close();
  1991. this.search.width(10);
  1992. } else {
  1993. if (this.countSelectableResults()>0) {
  1994. this.search.width(10);
  1995. this.resizeSearch();
  1996. if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
  1997. // if we reached max selection size repaint the results so choices
  1998. // are replaced with the max selection reached message
  1999. this.updateResults(true);
  2000. }
  2001. this.positionDropdown();
  2002. } else {
  2003. // if nothing left to select close
  2004. this.close();
  2005. this.search.width(10);
  2006. }
  2007. }
  2008. // since its not possible to select an element that has already been
  2009. // added we do not need to check if this is a new element before firing change
  2010. this.triggerChange({ added: data });
  2011. if (!options || !options.noFocus)
  2012. this.focusSearch();
  2013. },
  2014. // multi
  2015. cancel: function () {
  2016. this.close();
  2017. this.focusSearch();
  2018. },
  2019. addSelectedChoice: function (data) {
  2020. var enableChoice = !data.locked,
  2021. enabledItem = $(
  2022. "<li class='select2-search-choice'>" +
  2023. " <div></div>" +
  2024. " <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
  2025. "</li>"),
  2026. disabledItem = $(
  2027. "<li class='select2-search-choice select2-locked'>" +
  2028. "<div></div>" +
  2029. "</li>");
  2030. var choice = enableChoice ? enabledItem : disabledItem,
  2031. id = this.id(data),
  2032. val = this.getVal(),
  2033. formatted;
  2034. formatted=this.opts.formatSelection(data, choice.find("div"));
  2035. if (formatted != undefined) {
  2036. choice.find("div").replaceWith("<div>"+this.opts.escapeMarkup(formatted)+"</div>");
  2037. }
  2038. if(enableChoice){
  2039. choice.find(".select2-search-choice-close")
  2040. .bind("mousedown", killEvent)
  2041. .bind("click dblclick", this.bind(function (e) {
  2042. if (!this.enabled) return;
  2043. $(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
  2044. this.unselect($(e.target));
  2045. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  2046. this.close();
  2047. this.focusSearch();
  2048. })).dequeue();
  2049. killEvent(e);
  2050. })).bind("focus", this.bind(function () {
  2051. if (!this.enabled) return;
  2052. this.container.addClass("select2-container-active");
  2053. this.dropdown.addClass("select2-drop-active");
  2054. }));
  2055. }
  2056. choice.data("select2-data", data);
  2057. choice.insertBefore(this.searchContainer);
  2058. val.push(id);
  2059. this.setVal(val);
  2060. },
  2061. // multi
  2062. unselect: function (selected) {
  2063. var val = this.getVal(),
  2064. data,
  2065. index;
  2066. selected = selected.closest(".select2-search-choice");
  2067. if (selected.length === 0) {
  2068. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  2069. }
  2070. data = selected.data("select2-data");
  2071. if (!data) {
  2072. // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
  2073. // and invoked on an element already removed
  2074. return;
  2075. }
  2076. index = indexOf(this.id(data), val);
  2077. if (index >= 0) {
  2078. val.splice(index, 1);
  2079. this.setVal(val);
  2080. if (this.select) this.postprocessResults();
  2081. }
  2082. selected.remove();
  2083. this.opts.element.trigger({ type: "removed", val: this.id(data), choice: data });
  2084. this.triggerChange({ removed: data });
  2085. },
  2086. // multi
  2087. postprocessResults: function () {
  2088. var val = this.getVal(),
  2089. choices = this.results.find(".select2-result"),
  2090. compound = this.results.find(".select2-result-with-children"),
  2091. self = this;
  2092. choices.each2(function (i, choice) {
  2093. var id = self.id(choice.data("select2-data"));
  2094. if (indexOf(id, val) >= 0) {
  2095. choice.addClass("select2-selected");
  2096. // mark all children of the selected parent as selected
  2097. choice.find(".select2-result-selectable").addClass("select2-selected");
  2098. }
  2099. });
  2100. compound.each2(function(i, choice) {
  2101. // hide an optgroup if it doesnt have any selectable children
  2102. if (!choice.is('.select2-result-selectable')
  2103. && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
  2104. choice.addClass("select2-selected");
  2105. }
  2106. });
  2107. if (this.highlight() == -1){
  2108. self.highlight(0);
  2109. }
  2110. },
  2111. // multi
  2112. getMaxSearchWidth: function() {
  2113. return this.selection.width() - getSideBorderPadding(this.search);
  2114. },
  2115. // multi
  2116. resizeSearch: function () {
  2117. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  2118. sideBorderPadding = getSideBorderPadding(this.search);
  2119. minimumWidth = measureTextWidth(this.search) + 10;
  2120. left = this.search.offset().left;
  2121. maxWidth = this.selection.width();
  2122. containerLeft = this.selection.offset().left;
  2123. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  2124. if (searchWidth < minimumWidth) {
  2125. searchWidth = maxWidth - sideBorderPadding;
  2126. }
  2127. if (searchWidth < 40) {
  2128. searchWidth = maxWidth - sideBorderPadding;
  2129. }
  2130. if (searchWidth <= 0) {
  2131. searchWidth = minimumWidth;
  2132. }
  2133. this.search.width(searchWidth);
  2134. },
  2135. // multi
  2136. getVal: function () {
  2137. var val;
  2138. if (this.select) {
  2139. val = this.select.val();
  2140. return val === null ? [] : val;
  2141. } else {
  2142. val = this.opts.element.val();
  2143. return splitVal(val, this.opts.separator);
  2144. }
  2145. },
  2146. // multi
  2147. setVal: function (val) {
  2148. var unique;
  2149. if (this.select) {
  2150. this.select.val(val);
  2151. } else {
  2152. unique = [];
  2153. // filter out duplicates
  2154. $(val).each(function () {
  2155. if (indexOf(this, unique) < 0) unique.push(this);
  2156. });
  2157. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  2158. }
  2159. },
  2160. // multi
  2161. val: function () {
  2162. var val, triggerChange = false, data = [], self=this;
  2163. if (arguments.length === 0) {
  2164. return this.getVal();
  2165. }
  2166. val = arguments[0];
  2167. if (arguments.length > 1) {
  2168. triggerChange = arguments[1];
  2169. }
  2170. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2171. if (!val && val !== 0) {
  2172. this.opts.element.val("");
  2173. this.updateSelection([]);
  2174. this.clearSearch();
  2175. if (triggerChange) {
  2176. this.triggerChange();
  2177. }
  2178. return;
  2179. }
  2180. // val is a list of ids
  2181. this.setVal(val);
  2182. if (this.select) {
  2183. this.opts.initSelection(this.select, this.bind(this.updateSelection));
  2184. if (triggerChange) {
  2185. this.triggerChange();
  2186. }
  2187. } else {
  2188. if (this.opts.initSelection === undefined) {
  2189. throw new Error("val() cannot be called if initSelection() is not defined");
  2190. }
  2191. this.opts.initSelection(this.opts.element, function(data){
  2192. var ids=$(data).map(self.id);
  2193. self.setVal(ids);
  2194. self.updateSelection(data);
  2195. self.clearSearch();
  2196. if (triggerChange) {
  2197. self.triggerChange();
  2198. }
  2199. });
  2200. }
  2201. this.clearSearch();
  2202. },
  2203. // multi
  2204. onSortStart: function() {
  2205. if (this.select) {
  2206. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  2207. }
  2208. // collapse search field into 0 width so its container can be collapsed as well
  2209. this.search.width(0);
  2210. // hide the container
  2211. this.searchContainer.hide();
  2212. },
  2213. // multi
  2214. onSortEnd:function() {
  2215. var val=[], self=this;
  2216. // show search and move it to the end of the list
  2217. this.searchContainer.show();
  2218. // make sure the search container is the last item in the list
  2219. this.searchContainer.appendTo(this.searchContainer.parent());
  2220. // since we collapsed the width in dragStarted, we resize it here
  2221. this.resizeSearch();
  2222. // update selection
  2223. this.selection.find(".select2-search-choice").each(function() {
  2224. val.push(self.opts.id($(this).data("select2-data")));
  2225. });
  2226. this.setVal(val);
  2227. this.triggerChange();
  2228. },
  2229. // multi
  2230. data: function(values) {
  2231. var self=this, ids;
  2232. if (arguments.length === 0) {
  2233. return this.selection
  2234. .find(".select2-search-choice")
  2235. .map(function() { return $(this).data("select2-data"); })
  2236. .get();
  2237. } else {
  2238. if (!values) { values = []; }
  2239. ids = $.map(values, function(e) { return self.opts.id(e); });
  2240. this.setVal(ids);
  2241. this.updateSelection(values);
  2242. this.clearSearch();
  2243. }
  2244. }
  2245. });
  2246. $.fn.select2 = function () {
  2247. var args = Array.prototype.slice.call(arguments, 0),
  2248. opts,
  2249. select2,
  2250. value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
  2251. this.each(function () {
  2252. if (args.length === 0 || typeof(args[0]) === "object") {
  2253. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  2254. opts.element = $(this);
  2255. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2256. multiple = opts.element.attr("multiple");
  2257. } else {
  2258. multiple = opts.multiple || false;
  2259. if ("tags" in opts) {opts.multiple = multiple = true;}
  2260. }
  2261. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  2262. select2.init(opts);
  2263. } else if (typeof(args[0]) === "string") {
  2264. if (indexOf(args[0], allowedMethods) < 0) {
  2265. throw "Unknown method: " + args[0];
  2266. }
  2267. value = undefined;
  2268. select2 = $(this).data("select2");
  2269. if (select2 === undefined) return;
  2270. if (args[0] === "container") {
  2271. value=select2.container;
  2272. } else {
  2273. value = select2[args[0]].apply(select2, args.slice(1));
  2274. }
  2275. if (value !== undefined) {return false;}
  2276. } else {
  2277. throw "Invalid arguments to select2 plugin: " + args;
  2278. }
  2279. });
  2280. return (value === undefined) ? this : value;
  2281. };
  2282. // plugin defaults, accessible to users
  2283. $.fn.select2.defaults = {
  2284. width: "copy",
  2285. loadMorePadding: 0,
  2286. closeOnSelect: true,
  2287. openOnEnter: true,
  2288. containerCss: {},
  2289. dropdownCss: {},
  2290. containerCssClass: "",
  2291. dropdownCssClass: "",
  2292. formatResult: function(result, container, query, escapeMarkup) {
  2293. var markup=[];
  2294. markMatch(result.text, query.term, markup, escapeMarkup);
  2295. return markup.join("");
  2296. },
  2297. formatSelection: function (data, container) {
  2298. return data ? data.text : undefined;
  2299. },
  2300. sortResults: function (results, container, query) {
  2301. return results;
  2302. },
  2303. formatResultCssClass: function(data) {return undefined;},
  2304. formatNoMatches: function () { return "No matches found"; },
  2305. formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); },
  2306. formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
  2307. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
  2308. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  2309. formatSearching: function () { return "Searching..."; },
  2310. minimumResultsForSearch: 0,
  2311. minimumInputLength: 0,
  2312. maximumInputLength: null,
  2313. maximumSelectionSize: 0,
  2314. id: function (e) { return e.id; },
  2315. matcher: function(term, text) {
  2316. return (''+text).toUpperCase().indexOf((''+term).toUpperCase()) >= 0;
  2317. },
  2318. separator: ",",
  2319. tokenSeparators: [],
  2320. tokenizer: defaultTokenizer,
  2321. escapeMarkup: function (markup) {
  2322. var replace_map = {
  2323. '\\': '&#92;',
  2324. '&': '&amp;',
  2325. '<': '&lt;',
  2326. '>': '&gt;',
  2327. '"': '&quot;',
  2328. "'": '&apos;',
  2329. "/": '&#47;'
  2330. };
  2331. return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
  2332. return replace_map[match[0]];
  2333. });
  2334. },
  2335. blurOnChange: false,
  2336. selectOnBlur: false,
  2337. adaptContainerCssClass: function(c) { return c; },
  2338. adaptDropdownCssClass: function(c) { return null; }
  2339. };
  2340. // exports
  2341. window.Select2 = {
  2342. query: {
  2343. ajax: ajax,
  2344. local: local,
  2345. tags: tags
  2346. }, util: {
  2347. debounce: debounce,
  2348. markMatch: markMatch
  2349. }, "class": {
  2350. "abstract": AbstractSelect2,
  2351. "single": SingleSelect2,
  2352. "multi": MultiSelect2
  2353. }
  2354. };
  2355. }(jQuery));