select2.js 59 KB

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