select2.js 88 KB

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