select2.js 106 KB

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