select2.js 87 KB

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