select2.js 113 KB

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