select2.js 112 KB

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