select2.js 64 KB

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