select2.js 71 KB

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