select2.js 87 KB

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