select2.js 62 KB

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