select2.js 98 KB

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