select2.js 94 KB

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