select2.js 99 KB

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