select2.js 107 KB

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