select2.js 54 KB

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