select2.js 98 KB

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