select2.js 99 KB

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