select2.js 77 KB

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