select2.js 88 KB

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