select2.js 88 KB

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