select2.js 96 KB

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