select2.js 60 KB

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