select2.js 81 KB

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