select2.js 77 KB

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