select2.js 95 KB

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