select2.js 106 KB

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