select2.js 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694
  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. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  529. this.container.css(evaluate(opts.containerCss));
  530. this.container.addClass(evaluate(opts.containerCssClass));
  531. this.elementTabIndex = this.opts.element.attr("tabIndex");
  532. // swap container for the element
  533. this.opts.element
  534. .data("select2", this)
  535. .addClass("select2-offscreen")
  536. .bind("focus.select2", function() { $(this).select2("focus"); })
  537. .attr("tabIndex", "-1")
  538. .before(this.container);
  539. this.container.data("select2", this);
  540. this.dropdown = this.container.find(".select2-drop");
  541. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  542. this.dropdown.data("select2", this);
  543. this.results = results = this.container.find(resultsSelector);
  544. this.search = search = this.container.find("input.select2-input");
  545. search.attr("tabIndex", this.elementTabIndex);
  546. this.resultsPage = 0;
  547. this.context = null;
  548. // initialize the container
  549. this.initContainer();
  550. this.initContainerWidth();
  551. installFilteredMouseMove(this.results);
  552. this.dropdown.delegate(resultsSelector, "mousemove-filtered touchstart touchmove touchend", this.bind(this.highlightUnderEvent));
  553. installDebouncedScroll(80, this.results);
  554. this.dropdown.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  555. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  556. if ($.fn.mousewheel) {
  557. results.mousewheel(function (e, delta, deltaX, deltaY) {
  558. var top = results.scrollTop(), height;
  559. if (deltaY > 0 && top - deltaY <= 0) {
  560. results.scrollTop(0);
  561. killEvent(e);
  562. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  563. results.scrollTop(results.get(0).scrollHeight - results.height());
  564. killEvent(e);
  565. }
  566. });
  567. }
  568. installKeyUpChangeEvent(search);
  569. search.bind("keyup-change input paste", this.bind(this.updateResults));
  570. search.bind("focus", function () { search.addClass("select2-focused"); });
  571. search.bind("blur", function () { search.removeClass("select2-focused");});
  572. this.dropdown.delegate(resultsSelector, "mouseup", this.bind(function (e) {
  573. if ($(e.target).closest(".select2-result-selectable").length > 0) {
  574. this.highlightUnderEvent(e);
  575. this.selectHighlighted(e);
  576. } else {
  577. this.focusSearch();
  578. }
  579. killEvent(e);
  580. }));
  581. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  582. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  583. // dom it will trigger the popup close, which is not what we want
  584. this.dropdown.bind("click mouseup mousedown", function (e) { e.stopPropagation(); });
  585. if ($.isFunction(this.opts.initSelection)) {
  586. // initialize selection based on the current value of the source element
  587. this.initSelection();
  588. // if the user has provided a function that can set selection based on the value of the source element
  589. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  590. this.monitorSource();
  591. }
  592. if (opts.element.is(":disabled") || opts.element.is("[readonly='readonly']")) this.disable();
  593. },
  594. // abstract
  595. destroy: function () {
  596. var select2 = this.opts.element.data("select2");
  597. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  598. if (select2 !== undefined) {
  599. select2.container.remove();
  600. select2.dropdown.remove();
  601. select2.opts.element
  602. .removeClass("select2-offscreen")
  603. .removeData("select2")
  604. .unbind(".select2")
  605. .attr({"tabIndex": this.elementTabIndex})
  606. .show();
  607. }
  608. },
  609. // abstract
  610. prepareOpts: function (opts) {
  611. var element, select, idKey, ajaxUrl;
  612. element = opts.element;
  613. if (element.get(0).tagName.toLowerCase() === "select") {
  614. this.select = select = opts.element;
  615. }
  616. if (select) {
  617. // these options are not allowed when attached to a select because they are picked up off the element itself
  618. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  619. if (this in opts) {
  620. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  621. }
  622. });
  623. }
  624. opts = $.extend({}, {
  625. populateResults: function(container, results, query) {
  626. var populate, data, result, children, id=this.opts.id, self=this;
  627. populate=function(results, container, depth) {
  628. var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
  629. results = opts.sortResults(results, container, query);
  630. for (i = 0, l = results.length; i < l; i = i + 1) {
  631. result=results[i];
  632. disabled = (result.disabled === true);
  633. selectable = (!disabled) && (id(result) !== undefined);
  634. compound=result.children && result.children.length > 0;
  635. node=$("<li></li>");
  636. node.addClass("select2-results-dept-"+depth);
  637. node.addClass("select2-result");
  638. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  639. if (disabled) { node.addClass("select2-disabled"); }
  640. if (compound) { node.addClass("select2-result-with-children"); }
  641. node.addClass(self.opts.formatResultCssClass(result));
  642. label=$(document.createElement("div"));
  643. label.addClass("select2-result-label");
  644. formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
  645. if (formatted!==undefined) {
  646. label.html(formatted);
  647. }
  648. node.append(label);
  649. if (compound) {
  650. innerContainer=$("<ul></ul>");
  651. innerContainer.addClass("select2-result-sub");
  652. populate(result.children, innerContainer, depth+1);
  653. node.append(innerContainer);
  654. }
  655. node.data("select2-data", result);
  656. container.append(node);
  657. }
  658. };
  659. populate(results, container, 0);
  660. }
  661. }, $.fn.select2.defaults, opts);
  662. if (typeof(opts.id) !== "function") {
  663. idKey = opts.id;
  664. opts.id = function (e) { return e[idKey]; };
  665. }
  666. if ($.isArray(opts.element.data("select2Tags"))) {
  667. if ("tags" in opts) {
  668. throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
  669. }
  670. opts.tags=opts.element.attr("data-select2-tags");
  671. }
  672. if (select) {
  673. opts.query = this.bind(function (query) {
  674. var data = { results: [], more: false },
  675. term = query.term,
  676. children, firstChild, process;
  677. process=function(element, collection) {
  678. var group;
  679. if (element.is("option")) {
  680. if (query.matcher(term, element.text(), element)) {
  681. collection.push({id:element.attr("value"), text:element.text(), element: element.get(), css: element.attr("class"), disabled: equal(element.attr("disabled"), "disabled") });
  682. }
  683. } else if (element.is("optgroup")) {
  684. group={text:element.attr("label"), children:[], element: element.get(), css: element.attr("class")};
  685. element.children().each2(function(i, elm) { process(elm, group.children); });
  686. if (group.children.length>0) {
  687. collection.push(group);
  688. }
  689. }
  690. };
  691. children=element.children();
  692. // ignore the placeholder option if there is one
  693. if (this.getPlaceholder() !== undefined && children.length > 0) {
  694. firstChild = children[0];
  695. if ($(firstChild).text() === "") {
  696. children=children.not(firstChild);
  697. }
  698. }
  699. children.each2(function(i, elm) { process(elm, data.results); });
  700. query.callback(data);
  701. });
  702. // this is needed because inside val() we construct choices from options and there id is hardcoded
  703. opts.id=function(e) { return e.id; };
  704. opts.formatResultCssClass = function(data) { return data.css; };
  705. } else {
  706. if (!("query" in opts)) {
  707. if ("ajax" in opts) {
  708. ajaxUrl = opts.element.data("ajax-url");
  709. if (ajaxUrl && ajaxUrl.length > 0) {
  710. opts.ajax.url = ajaxUrl;
  711. }
  712. opts.query = ajax(opts.ajax);
  713. } else if ("data" in opts) {
  714. opts.query = local(opts.data);
  715. } else if ("tags" in opts) {
  716. opts.query = tags(opts.tags);
  717. if (opts.createSearchChoice === undefined) {
  718. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  719. }
  720. if (opts.initSelection === undefined) {
  721. opts.initSelection = function (element, callback) {
  722. var data = [];
  723. $(splitVal(element.val(), opts.separator)).each(function () {
  724. var id = this, text = this, tags=opts.tags;
  725. if ($.isFunction(tags)) tags=tags();
  726. $(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } });
  727. data.push({id: id, text: text});
  728. });
  729. callback(data);
  730. };
  731. }
  732. }
  733. }
  734. }
  735. if (typeof(opts.query) !== "function") {
  736. throw "query function not defined for Select2 " + opts.element.attr("id");
  737. }
  738. return opts;
  739. },
  740. /**
  741. * Monitor the original element for changes and update select2 accordingly
  742. */
  743. // abstract
  744. monitorSource: function () {
  745. var el = this.opts.element, sync;
  746. el.bind("change.select2", this.bind(function (e) {
  747. if (this.opts.element.data("select2-change-triggered") !== true) {
  748. this.initSelection();
  749. }
  750. }));
  751. sync = this.bind(function () {
  752. var enabled, readonly, self = this;
  753. // sync enabled state
  754. enabled = this.opts.element.attr("disabled") !== "disabled";
  755. readonly = this.opts.element.attr("readonly") === "readonly";
  756. enabled = enabled && !readonly;
  757. if (this.enabled !== enabled) {
  758. if (enabled) {
  759. this.enable();
  760. } else {
  761. this.disable();
  762. }
  763. }
  764. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  765. this.container.addClass(evaluate(this.opts.containerCssClass));
  766. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  767. this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
  768. });
  769. // mozilla and IE
  770. el.bind("propertychange.select2 DOMAttrModified.select2", sync);
  771. // safari and chrome
  772. if (typeof WebKitMutationObserver !== "undefined") {
  773. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  774. this.propertyObserver = new WebKitMutationObserver(function (mutations) {
  775. mutations.forEach(sync);
  776. });
  777. this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
  778. }
  779. },
  780. /**
  781. * Triggers the change event on the source element
  782. */
  783. // abstract
  784. triggerChange: function (details) {
  785. details = details || {};
  786. details= $.extend({}, details, { type: "change", val: this.val() });
  787. // prevents recursive triggering
  788. this.opts.element.data("select2-change-triggered", true);
  789. this.opts.element.trigger(details);
  790. this.opts.element.data("select2-change-triggered", false);
  791. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  792. // so here we trigger the click event manually
  793. this.opts.element.click();
  794. // ValidationEngine ignorea the change event and listens instead to blur
  795. // so here we trigger the blur event manually if so desired
  796. if (this.opts.blurOnChange)
  797. this.opts.element.blur();
  798. },
  799. // abstract
  800. enable: function() {
  801. if (this.enabled) return;
  802. this.enabled=true;
  803. this.container.removeClass("select2-container-disabled");
  804. this.opts.element.removeAttr("disabled");
  805. },
  806. // abstract
  807. disable: function() {
  808. if (!this.enabled) return;
  809. this.close();
  810. this.enabled=false;
  811. this.container.addClass("select2-container-disabled");
  812. this.opts.element.attr("disabled", "disabled");
  813. },
  814. // abstract
  815. opened: function () {
  816. return this.container.hasClass("select2-dropdown-open");
  817. },
  818. // abstract
  819. positionDropdown: function() {
  820. var offset = this.container.offset(),
  821. height = this.container.outerHeight(false),
  822. width = this.container.outerWidth(false),
  823. dropHeight = this.dropdown.outerHeight(false),
  824. viewPortRight = $(window).scrollLeft() + $(window).width(),
  825. viewportBottom = $(window).scrollTop() + $(window).height(),
  826. dropTop = offset.top + height,
  827. dropLeft = offset.left,
  828. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  829. enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
  830. dropWidth = this.dropdown.outerWidth(false),
  831. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
  832. aboveNow = this.dropdown.hasClass("select2-drop-above"),
  833. bodyOffset,
  834. above,
  835. css;
  836. //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  837. //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  838. // fix positioning when body has an offset and is not position: static
  839. if (this.body().css('position') !== 'static') {
  840. bodyOffset = this.body().offset();
  841. dropTop -= bodyOffset.top;
  842. dropLeft -= bodyOffset.left;
  843. }
  844. // always prefer the current above/below alignment, unless there is not enough room
  845. if (aboveNow) {
  846. above = true;
  847. if (!enoughRoomAbove && enoughRoomBelow) above = false;
  848. } else {
  849. above = false;
  850. if (!enoughRoomBelow && enoughRoomAbove) above = true;
  851. }
  852. if (!enoughRoomOnRight) {
  853. dropLeft = offset.left + width - dropWidth;
  854. }
  855. if (above) {
  856. dropTop = offset.top - dropHeight;
  857. this.container.addClass("select2-drop-above");
  858. this.dropdown.addClass("select2-drop-above");
  859. }
  860. else {
  861. this.container.removeClass("select2-drop-above");
  862. this.dropdown.removeClass("select2-drop-above");
  863. }
  864. css = $.extend({
  865. top: dropTop,
  866. left: dropLeft,
  867. width: width
  868. }, evaluate(this.opts.dropdownCss));
  869. this.dropdown.css(css);
  870. },
  871. // abstract
  872. shouldOpen: function() {
  873. var event;
  874. if (this.opened()) return false;
  875. event = $.Event("opening");
  876. this.opts.element.trigger(event);
  877. return !event.isDefaultPrevented();
  878. },
  879. // abstract
  880. clearDropdownAlignmentPreference: function() {
  881. // clear the classes used to figure out the preference of where the dropdown should be opened
  882. this.container.removeClass("select2-drop-above");
  883. this.dropdown.removeClass("select2-drop-above");
  884. },
  885. /**
  886. * Opens the dropdown
  887. *
  888. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  889. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  890. */
  891. // abstract
  892. open: function () {
  893. if (!this.shouldOpen()) return false;
  894. window.setTimeout(this.bind(this.opening), 1);
  895. return true;
  896. },
  897. /**
  898. * Performs the opening of the dropdown
  899. */
  900. // abstract
  901. opening: function() {
  902. var cid = this.containerId,
  903. scroll = "scroll." + cid,
  904. resize = "resize."+cid,
  905. orient = "orientationchange."+cid,
  906. mask;
  907. this.clearDropdownAlignmentPreference();
  908. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  909. if(this.dropdown[0] !== this.body().children().last()[0]) {
  910. this.dropdown.detach().appendTo(this.body());
  911. }
  912. this.updateResults(true);
  913. // create the dropdown mask if doesnt already exist
  914. mask = $("#select2-drop-mask");
  915. if (mask.length == 0) {
  916. mask = $(document.createElement("div"));
  917. mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
  918. mask.hide();
  919. mask.appendTo(this.body());
  920. mask.bind("mousedown touchstart", function (e) {
  921. var dropdown = $("#select2-drop"), self;
  922. if (dropdown.length > 0) {
  923. self=dropdown.data("select2");
  924. if (self.opts.selectOnBlur) {
  925. self.selectHighlighted({noFocus: true});
  926. }
  927. self.close();
  928. }
  929. });
  930. }
  931. // ensure the mask is always right before the dropdown
  932. if (this.dropdown.prev()[0] !== mask[0]) {
  933. this.dropdown.before(mask);
  934. }
  935. // move the global id to the correct dropdown
  936. $("#select2-drop").removeAttr("id");
  937. this.dropdown.attr("id", "select2-drop");
  938. // show the elements
  939. mask.css({
  940. width: document.documentElement.scrollWidth,
  941. height: document.documentElement.scrollHeight});
  942. mask.show();
  943. this.dropdown.show();
  944. this.positionDropdown();
  945. this.dropdown.addClass("select2-drop-active");
  946. this.ensureHighlightVisible();
  947. // attach listeners to events that can change the position of the container and thus require
  948. // the position of the dropdown to be updated as well so it does not come unglued from the container
  949. this.container.parents().add(window).each(function () {
  950. $(this).bind(resize+" "+scroll+" "+orient, function (e) {
  951. $("#select2-drop-mask").css({
  952. width:document.documentElement.scrollWidth,
  953. height:document.documentElement.scrollHeight});
  954. $("#select2-drop").data("select2").positionDropdown();
  955. });
  956. });
  957. this.focusSearch();
  958. },
  959. // abstract
  960. close: function () {
  961. if (!this.opened()) return;
  962. var cid = this.containerId,
  963. scroll = "scroll." + cid,
  964. resize = "resize."+cid,
  965. orient = "orientationchange."+cid;
  966. // unbind event listeners
  967. this.container.parents().add(window).each(function () { $(this).unbind(scroll).unbind(resize).unbind(orient); });
  968. this.clearDropdownAlignmentPreference();
  969. $("#select2-drop-mask").hide();
  970. this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
  971. this.dropdown.hide();
  972. this.container.removeClass("select2-dropdown-open");
  973. this.results.empty();
  974. this.clearSearch();
  975. this.opts.element.trigger($.Event("close"));
  976. },
  977. // abstract
  978. clearSearch: function () {
  979. },
  980. //abstract
  981. getMaximumSelectionSize: function() {
  982. return evaluate(this.opts.maximumSelectionSize);
  983. },
  984. // abstract
  985. ensureHighlightVisible: function () {
  986. var results = this.results, children, index, child, hb, rb, y, more;
  987. index = this.highlight();
  988. if (index < 0) return;
  989. if (index == 0) {
  990. // if the first element is highlighted scroll all the way to the top,
  991. // that way any unselectable headers above it will also be scrolled
  992. // into view
  993. results.scrollTop(0);
  994. return;
  995. }
  996. children = this.findHighlightableChoices();
  997. child = $(children[index]);
  998. hb = child.offset().top + child.outerHeight(true);
  999. // if this is the last child lets also make sure select2-more-results is visible
  1000. if (index === children.length - 1) {
  1001. more = results.find("li.select2-more-results");
  1002. if (more.length > 0) {
  1003. hb = more.offset().top + more.outerHeight(true);
  1004. }
  1005. }
  1006. rb = results.offset().top + results.outerHeight(true);
  1007. if (hb > rb) {
  1008. results.scrollTop(results.scrollTop() + (hb - rb));
  1009. }
  1010. y = child.offset().top - results.offset().top;
  1011. // make sure the top of the element is visible
  1012. if (y < 0 && child.css('display') != 'none' ) {
  1013. results.scrollTop(results.scrollTop() + y); // y is negative
  1014. }
  1015. },
  1016. // abstract
  1017. findHighlightableChoices: function() {
  1018. var h=this.results.find(".select2-result-selectable:not(.select2-selected):not(.select2-disabled)");
  1019. return this.results.find(".select2-result-selectable:not(.select2-selected):not(.select2-disabled)");
  1020. },
  1021. // abstract
  1022. moveHighlight: function (delta) {
  1023. var choices = this.findHighlightableChoices(),
  1024. index = this.highlight();
  1025. while (index > -1 && index < choices.length) {
  1026. index += delta;
  1027. var choice = $(choices[index]);
  1028. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
  1029. this.highlight(index);
  1030. break;
  1031. }
  1032. }
  1033. },
  1034. // abstract
  1035. highlight: function (index) {
  1036. var choices = this.findHighlightableChoices(),
  1037. choice,
  1038. data;
  1039. if (arguments.length === 0) {
  1040. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  1041. }
  1042. if (index >= choices.length) index = choices.length - 1;
  1043. if (index < 0) index = 0;
  1044. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1045. choice = $(choices[index]);
  1046. choice.addClass("select2-highlighted");
  1047. this.ensureHighlightVisible();
  1048. data = choice.data("select2-data");
  1049. if (data) {
  1050. this.opts.element.trigger({ type: "highlight", val: this.id(data), choice: data });
  1051. }
  1052. },
  1053. // abstract
  1054. countSelectableResults: function() {
  1055. return this.findHighlightableChoices().length;
  1056. },
  1057. // abstract
  1058. highlightUnderEvent: function (event) {
  1059. var el = $(event.target).closest(".select2-result-selectable");
  1060. if (el.length > 0 && !el.is(".select2-highlighted")) {
  1061. var choices = this.findHighlightableChoices();
  1062. this.highlight(choices.index(el));
  1063. } else if (el.length == 0) {
  1064. // if we are over an unselectable item remove al highlights
  1065. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1066. }
  1067. },
  1068. // abstract
  1069. loadMoreIfNeeded: function () {
  1070. var results = this.results,
  1071. more = results.find("li.select2-more-results"),
  1072. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  1073. offset = -1, // index of first element without data
  1074. page = this.resultsPage + 1,
  1075. self=this,
  1076. term=this.search.val(),
  1077. context=this.context;
  1078. if (more.length === 0) return;
  1079. below = more.offset().top - results.offset().top - results.height();
  1080. if (below <= this.opts.loadMorePadding) {
  1081. more.addClass("select2-active");
  1082. this.opts.query({
  1083. element: this.opts.element,
  1084. term: term,
  1085. page: page,
  1086. context: context,
  1087. matcher: this.opts.matcher,
  1088. callback: this.bind(function (data) {
  1089. // ignore a response if the select2 has been closed before it was received
  1090. if (!self.opened()) return;
  1091. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  1092. if (data.more===true) {
  1093. more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
  1094. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1095. } else {
  1096. more.remove();
  1097. }
  1098. self.positionDropdown();
  1099. self.resultsPage = page;
  1100. self.context = data.context;
  1101. })});
  1102. }
  1103. },
  1104. /**
  1105. * Default tokenizer function which does nothing
  1106. */
  1107. tokenize: function() {
  1108. },
  1109. /**
  1110. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  1111. */
  1112. // abstract
  1113. updateResults: function (initial) {
  1114. var search = this.search, results = this.results, opts = this.opts, data, self=this, input;
  1115. // if the search is currently hidden we do not alter the results
  1116. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  1117. return;
  1118. }
  1119. search.addClass("select2-active");
  1120. function postRender() {
  1121. results.scrollTop(0);
  1122. search.removeClass("select2-active");
  1123. self.positionDropdown();
  1124. }
  1125. function render(html) {
  1126. results.html(html);
  1127. postRender();
  1128. }
  1129. var maxSelSize = this.getMaximumSelectionSize();
  1130. if (maxSelSize >=1) {
  1131. data = this.data();
  1132. if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  1133. render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>");
  1134. return;
  1135. }
  1136. }
  1137. if (search.val().length < opts.minimumInputLength) {
  1138. if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  1139. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  1140. } else {
  1141. render("");
  1142. }
  1143. return;
  1144. }
  1145. else if (opts.formatSearching() && initial===true) {
  1146. render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
  1147. }
  1148. if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
  1149. if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
  1150. render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>");
  1151. } else {
  1152. render("");
  1153. }
  1154. return;
  1155. }
  1156. // give the tokenizer a chance to pre-process the input
  1157. input = this.tokenize();
  1158. if (input != undefined && input != null) {
  1159. search.val(input);
  1160. }
  1161. this.resultsPage = 1;
  1162. opts.query({
  1163. element: opts.element,
  1164. term: search.val(),
  1165. page: this.resultsPage,
  1166. context: null,
  1167. matcher: opts.matcher,
  1168. callback: this.bind(function (data) {
  1169. var def; // default choice
  1170. // ignore a response if the select2 has been closed before it was received
  1171. if (!this.opened()) return;
  1172. // save context, if any
  1173. this.context = (data.context===undefined) ? null : data.context;
  1174. // create a default choice and prepend it to the list
  1175. if (this.opts.createSearchChoice && search.val() !== "") {
  1176. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  1177. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  1178. if ($(data.results).filter(
  1179. function () {
  1180. return equal(self.id(this), self.id(def));
  1181. }).length === 0) {
  1182. data.results.unshift(def);
  1183. }
  1184. }
  1185. }
  1186. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  1187. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  1188. return;
  1189. }
  1190. results.empty();
  1191. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  1192. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  1193. results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
  1194. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1195. }
  1196. this.postprocessResults(data, initial);
  1197. postRender();
  1198. })});
  1199. },
  1200. // abstract
  1201. cancel: function () {
  1202. this.close();
  1203. },
  1204. // abstract
  1205. blur: function () {
  1206. // if selectOnBlur == true, select the currently highlighted option
  1207. if (this.opts.selectOnBlur)
  1208. this.selectHighlighted({noFocus: true});
  1209. this.close();
  1210. this.container.removeClass("select2-container-active");
  1211. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  1212. if (this.search[0] === document.activeElement) { this.search.blur(); }
  1213. this.clearSearch();
  1214. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1215. },
  1216. // abstract
  1217. focusSearch: function () {
  1218. focus(this.search);
  1219. },
  1220. // abstract
  1221. selectHighlighted: function (options) {
  1222. var index=this.highlight(),
  1223. highlighted=this.results.find(".select2-highlighted"),
  1224. data = highlighted.closest('.select2-result').data("select2-data");
  1225. if (data) {
  1226. this.highlight(index);
  1227. this.onSelect(data, options);
  1228. }
  1229. },
  1230. // abstract
  1231. getPlaceholder: function () {
  1232. // if a placeholder is specified on a select without the first empty option ignore it
  1233. if (this.select) {
  1234. if (this.select.find("option").first().text() !== "") {
  1235. return undefined;
  1236. }
  1237. }
  1238. return this.opts.element.attr("placeholder") ||
  1239. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1240. this.opts.element.data("placeholder") ||
  1241. this.opts.placeholder;
  1242. },
  1243. /**
  1244. * Get the desired width for the container element. This is
  1245. * derived first from option `width` passed to select2, then
  1246. * the inline 'style' on the original element, and finally
  1247. * falls back to the jQuery calculated element width.
  1248. */
  1249. // abstract
  1250. initContainerWidth: function () {
  1251. function resolveContainerWidth() {
  1252. var style, attrs, matches, i, l;
  1253. if (this.opts.width === "off") {
  1254. return null;
  1255. } else if (this.opts.width === "element"){
  1256. return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
  1257. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1258. // check if there is inline style on the element that contains width
  1259. style = this.opts.element.attr('style');
  1260. if (style !== undefined) {
  1261. attrs = style.split(';');
  1262. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1263. matches = attrs[i].replace(/\s/g, '')
  1264. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  1265. if (matches !== null && matches.length >= 1)
  1266. return matches[1];
  1267. }
  1268. }
  1269. if (this.opts.width === "resolve") {
  1270. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1271. // when attached to input type=hidden or elements hidden via css
  1272. style = this.opts.element.css('width');
  1273. if (style.indexOf("%") > 0) return style;
  1274. // finally, fallback on the calculated width of the element
  1275. return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
  1276. }
  1277. return null;
  1278. } else if ($.isFunction(this.opts.width)) {
  1279. return this.opts.width();
  1280. } else {
  1281. return this.opts.width;
  1282. }
  1283. };
  1284. var width = resolveContainerWidth.call(this);
  1285. if (width !== null) {
  1286. this.container.css("width", width);
  1287. }
  1288. }
  1289. });
  1290. SingleSelect2 = clazz(AbstractSelect2, {
  1291. // single
  1292. createContainer: function () {
  1293. var container = $(document.createElement("div")).attr({
  1294. "class": "select2-container"
  1295. }).html([
  1296. "<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>",
  1297. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  1298. " <div><b></b></div>" ,
  1299. "</a>",
  1300. "<input class='select2-focusser select2-offscreen' type='text'/>",
  1301. "<div class='select2-drop' style='display:none'>" ,
  1302. " <div class='select2-search'>" ,
  1303. " <input type='text' autocomplete='off' class='select2-input'/>" ,
  1304. " </div>" ,
  1305. " <ul class='select2-results'>" ,
  1306. " </ul>" ,
  1307. "</div>"].join(""));
  1308. return container;
  1309. },
  1310. // single
  1311. disable: function() {
  1312. if (!this.enabled) return;
  1313. this.parent.disable.apply(this, arguments);
  1314. this.focusser.attr("disabled", "disabled");
  1315. },
  1316. // single
  1317. enable: function() {
  1318. if (this.enabled) return;
  1319. this.parent.enable.apply(this, arguments);
  1320. this.focusser.removeAttr("disabled");
  1321. },
  1322. // single
  1323. opening: function () {
  1324. this.parent.opening.apply(this, arguments);
  1325. this.focusser.attr("disabled", "disabled");
  1326. this.opts.element.trigger($.Event("open"));
  1327. },
  1328. // single
  1329. close: function () {
  1330. if (!this.opened()) return;
  1331. this.parent.close.apply(this, arguments);
  1332. this.focusser.removeAttr("disabled");
  1333. focus(this.focusser);
  1334. },
  1335. // single
  1336. focus: function () {
  1337. if (this.opened()) {
  1338. this.close();
  1339. } else {
  1340. this.focusser.removeAttr("disabled");
  1341. this.focusser.focus();
  1342. }
  1343. },
  1344. // single
  1345. isFocused: function () {
  1346. return this.container.hasClass("select2-container-active");
  1347. },
  1348. // single
  1349. cancel: function () {
  1350. this.parent.cancel.apply(this, arguments);
  1351. this.focusser.removeAttr("disabled");
  1352. this.focusser.focus();
  1353. },
  1354. // single
  1355. initContainer: function () {
  1356. var selection,
  1357. container = this.container,
  1358. dropdown = this.dropdown,
  1359. clickingInside = false;
  1360. this.showSearch(this.opts.minimumResultsForSearch >= 0);
  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. if (this.showSearchInput !== false) {
  1415. this.search.val(this.focusser.val());
  1416. }
  1417. this.focusser.val("");
  1418. killEvent(e);
  1419. }));
  1420. selection.delegate("abbr", "mousedown", this.bind(function (e) {
  1421. if (!this.enabled) return;
  1422. this.clear();
  1423. killEventImmediately(e);
  1424. this.close();
  1425. this.triggerChange();
  1426. this.selection.focus();
  1427. }));
  1428. selection.bind("mousedown", this.bind(function (e) {
  1429. clickingInside = true;
  1430. if (this.opened()) {
  1431. this.close();
  1432. } else if (this.enabled) {
  1433. this.open();
  1434. }
  1435. killEvent(e);
  1436. clickingInside = false;
  1437. }));
  1438. dropdown.bind("mousedown", this.bind(function() { this.search.focus(); }));
  1439. selection.bind("focus", this.bind(function(e) {
  1440. killEvent(e);
  1441. }));
  1442. this.focusser.bind("focus", this.bind(function(){
  1443. this.container.addClass("select2-container-active");
  1444. })).bind("blur", this.bind(function() {
  1445. if (!this.opened()) {
  1446. this.container.removeClass("select2-container-active");
  1447. }
  1448. }));
  1449. this.search.bind("focus", this.bind(function(){
  1450. this.container.addClass("select2-container-active");
  1451. }))
  1452. this.setPlaceholder();
  1453. },
  1454. // single
  1455. clear: function() {
  1456. var data=this.selection.data("select2-data");
  1457. this.opts.element.val("");
  1458. this.selection.find("span").empty();
  1459. this.selection.removeData("select2-data");
  1460. this.setPlaceholder();
  1461. this.opts.element.trigger({ type: "removed", val: this.id(data), choice: data });
  1462. this.triggerChange({removed:data});
  1463. },
  1464. /**
  1465. * Sets selection based on source element's value
  1466. */
  1467. // single
  1468. initSelection: function () {
  1469. var selected;
  1470. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  1471. this.close();
  1472. this.setPlaceholder();
  1473. } else {
  1474. var self = this;
  1475. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1476. if (selected !== undefined && selected !== null) {
  1477. self.updateSelection(selected);
  1478. self.close();
  1479. self.setPlaceholder();
  1480. }
  1481. });
  1482. }
  1483. },
  1484. // single
  1485. prepareOpts: function () {
  1486. var opts = this.parent.prepareOpts.apply(this, arguments);
  1487. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1488. // install the selection initializer
  1489. opts.initSelection = function (element, callback) {
  1490. var selected = element.find(":selected");
  1491. // a single select box always has a value, no need to null check 'selected'
  1492. if ($.isFunction(callback))
  1493. callback({id: selected.attr("value"), text: selected.text(), element:selected});
  1494. };
  1495. } else if ("data" in opts) {
  1496. // install default initSelection when applied to hidden input and data is local
  1497. opts.initSelection = opts.initSelection || function (element, callback) {
  1498. var id = element.val();
  1499. //search in data by id
  1500. opts.query({
  1501. matcher: function(term, text, el){
  1502. return equal(id, opts.id(el));
  1503. },
  1504. callback: !$.isFunction(callback) ? $.noop : function(filtered) {
  1505. callback(filtered.results.length ? filtered.results[0] : null);
  1506. }
  1507. });
  1508. };
  1509. }
  1510. return opts;
  1511. },
  1512. // single
  1513. setPlaceholder: function () {
  1514. var placeholder = this.getPlaceholder();
  1515. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1516. // check for a first blank option if attached to a select
  1517. if (this.select && this.select.find("option:first").text() !== "") return;
  1518. this.selection.find("span").html(this.opts.escapeMarkup(placeholder));
  1519. this.selection.addClass("select2-default");
  1520. this.selection.find("abbr").hide();
  1521. }
  1522. },
  1523. // single
  1524. postprocessResults: function (data, initial) {
  1525. var selected = 0, self = this, showSearchInput = true;
  1526. // find the selected element in the result list
  1527. this.findHighlightableChoices().each2(function (i, elm) {
  1528. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1529. selected = i;
  1530. return false;
  1531. }
  1532. });
  1533. // and highlight it
  1534. this.highlight(selected);
  1535. // hide the search box if this is the first we got the results and there are a few of them
  1536. if (initial === true) {
  1537. var min=this.opts.minimumResultsForSearch;
  1538. showSearchInput = min < 0 ? false : countResults(data.results) >= min;
  1539. this.showSearch(showSearchInput);
  1540. }
  1541. },
  1542. // single
  1543. showSearch: function(showSearchInput) {
  1544. this.showSearchInput = showSearchInput;
  1545. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1546. //add "select2-with-searchbox" to the container if search box is shown
  1547. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1548. },
  1549. // single
  1550. onSelect: function (data, options) {
  1551. var old = this.opts.element.val();
  1552. this.opts.element.val(this.id(data));
  1553. this.updateSelection(data);
  1554. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  1555. this.close();
  1556. if (!options || !options.noFocus)
  1557. this.selection.focus();
  1558. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1559. },
  1560. // single
  1561. updateSelection: function (data) {
  1562. var container=this.selection.find("span"), formatted;
  1563. this.selection.data("select2-data", data);
  1564. container.empty();
  1565. formatted=this.opts.formatSelection(data, container);
  1566. if (formatted !== undefined) {
  1567. container.append(this.opts.escapeMarkup(formatted));
  1568. }
  1569. this.selection.removeClass("select2-default");
  1570. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1571. this.selection.find("abbr").show();
  1572. }
  1573. },
  1574. // single
  1575. val: function () {
  1576. var val, triggerChange = false, data = null, self = this;
  1577. if (arguments.length === 0) {
  1578. return this.opts.element.val();
  1579. }
  1580. val = arguments[0];
  1581. if (arguments.length > 1) {
  1582. triggerChange = arguments[1];
  1583. }
  1584. if (this.select) {
  1585. this.select
  1586. .val(val)
  1587. .find(":selected").each2(function (i, elm) {
  1588. data = {id: elm.attr("value"), text: elm.text()};
  1589. return false;
  1590. });
  1591. this.updateSelection(data);
  1592. this.setPlaceholder();
  1593. if (triggerChange) {
  1594. this.triggerChange();
  1595. }
  1596. } else {
  1597. if (this.opts.initSelection === undefined) {
  1598. throw new Error("cannot call val() if initSelection() is not defined");
  1599. }
  1600. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  1601. if (!val && val !== 0) {
  1602. this.clear();
  1603. if (triggerChange) {
  1604. this.triggerChange();
  1605. }
  1606. return;
  1607. }
  1608. this.opts.element.val(val);
  1609. this.opts.initSelection(this.opts.element, function(data){
  1610. self.opts.element.val(!data ? "" : self.id(data));
  1611. self.updateSelection(data);
  1612. self.setPlaceholder();
  1613. if (triggerChange) {
  1614. self.triggerChange();
  1615. }
  1616. });
  1617. }
  1618. },
  1619. // single
  1620. clearSearch: function () {
  1621. this.search.val("");
  1622. this.focusser.val("");
  1623. },
  1624. // single
  1625. data: function(value) {
  1626. var data;
  1627. if (arguments.length === 0) {
  1628. data = this.selection.data("select2-data");
  1629. if (data == undefined) data = null;
  1630. return data;
  1631. } else {
  1632. if (!value || value === "") {
  1633. this.clear();
  1634. } else {
  1635. this.opts.element.val(!value ? "" : this.id(value));
  1636. this.updateSelection(value);
  1637. }
  1638. }
  1639. }
  1640. });
  1641. MultiSelect2 = clazz(AbstractSelect2, {
  1642. // multi
  1643. createContainer: function () {
  1644. var container = $(document.createElement("div")).attr({
  1645. "class": "select2-container select2-container-multi"
  1646. }).html([
  1647. " <ul class='select2-choices'>",
  1648. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1649. " <li class='select2-search-field'>" ,
  1650. " <input type='text' autocomplete='off' class='select2-input'>" ,
  1651. " </li>" ,
  1652. "</ul>" ,
  1653. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1654. " <ul class='select2-results'>" ,
  1655. " </ul>" ,
  1656. "</div>"].join(""));
  1657. return container;
  1658. },
  1659. // multi
  1660. prepareOpts: function () {
  1661. var opts = this.parent.prepareOpts.apply(this, arguments);
  1662. // TODO validate placeholder is a string if specified
  1663. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1664. // install sthe selection initializer
  1665. opts.initSelection = function (element, callback) {
  1666. var data = [];
  1667. element.find(":selected").each2(function (i, elm) {
  1668. data.push({id: elm.attr("value"), text: elm.text(), element: elm[0]});
  1669. });
  1670. callback(data);
  1671. };
  1672. } else if ("data" in opts) {
  1673. // install default initSelection when applied to hidden input and data is local
  1674. opts.initSelection = opts.initSelection || function (element, callback) {
  1675. var ids = splitVal(element.val(), opts.separator);
  1676. //search in data by array of ids
  1677. opts.query({
  1678. matcher: function(term, text, el){
  1679. return $.grep(ids, function(id) {
  1680. return equal(id, opts.id(el));
  1681. }).length;
  1682. },
  1683. callback: !$.isFunction(callback) ? $.noop : function(filtered) {
  1684. callback(filtered.results);
  1685. }
  1686. });
  1687. };
  1688. }
  1689. return opts;
  1690. },
  1691. // multi
  1692. initContainer: function () {
  1693. var selector = ".select2-choices", selection;
  1694. this.searchContainer = this.container.find(".select2-search-field");
  1695. this.selection = selection = this.container.find(selector);
  1696. this.search.bind("input paste", this.bind(function() {
  1697. if (!this.enabled) return;
  1698. if (!this.opened()) {
  1699. this.open();
  1700. }
  1701. }));
  1702. this.search.bind("keydown", this.bind(function (e) {
  1703. if (!this.enabled) return;
  1704. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1705. this.close();
  1706. var choices,
  1707. selected = selection.find(".select2-search-choice-focus");
  1708. if (selected.length > 0) {
  1709. this.unselect(selected.first());
  1710. this.search.width(10);
  1711. killEvent(e);
  1712. return;
  1713. }
  1714. choices = selection.find(".select2-search-choice:not(.select2-locked)");
  1715. if (choices.length > 0) {
  1716. choices.last().addClass("select2-search-choice-focus");
  1717. }
  1718. } else {
  1719. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1720. }
  1721. if (this.opened()) {
  1722. switch (e.which) {
  1723. case KEY.UP:
  1724. case KEY.DOWN:
  1725. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1726. killEvent(e);
  1727. return;
  1728. case KEY.ENTER:
  1729. case KEY.TAB:
  1730. this.selectHighlighted();
  1731. killEvent(e);
  1732. return;
  1733. case KEY.ESC:
  1734. this.cancel(e);
  1735. killEvent(e);
  1736. return;
  1737. }
  1738. }
  1739. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  1740. || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1741. return;
  1742. }
  1743. if (e.which === KEY.ENTER) {
  1744. if (this.opts.openOnEnter === false) {
  1745. return;
  1746. } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
  1747. return;
  1748. }
  1749. }
  1750. this.open();
  1751. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1752. // prevent the page from scrolling
  1753. killEvent(e);
  1754. }
  1755. }));
  1756. this.search.bind("keyup", this.bind(this.resizeSearch));
  1757. this.search.bind("blur", this.bind(function(e) {
  1758. this.container.removeClass("select2-container-active");
  1759. this.search.removeClass("select2-focused");
  1760. if (!this.opened()) this.clearSearch();
  1761. e.stopImmediatePropagation();
  1762. }));
  1763. this.container.delegate(selector, "mousedown", this.bind(function (e) {
  1764. if (!this.enabled) return;
  1765. if ($(e.target).closest(".select2-search-choice").length > 0) {
  1766. // clicked inside a select2 search choice, do not open
  1767. return;
  1768. }
  1769. this.clearPlaceholder();
  1770. this.open();
  1771. this.focusSearch();
  1772. e.preventDefault();
  1773. }));
  1774. this.container.delegate(selector, "focus", this.bind(function () {
  1775. if (!this.enabled) return;
  1776. this.container.addClass("select2-container-active");
  1777. this.dropdown.addClass("select2-drop-active");
  1778. this.clearPlaceholder();
  1779. }));
  1780. // set the placeholder if necessary
  1781. this.clearSearch();
  1782. },
  1783. // multi
  1784. enable: function() {
  1785. if (this.enabled) return;
  1786. this.parent.enable.apply(this, arguments);
  1787. this.search.removeAttr("disabled");
  1788. },
  1789. // multi
  1790. disable: function() {
  1791. if (!this.enabled) return;
  1792. this.parent.disable.apply(this, arguments);
  1793. this.search.attr("disabled", true);
  1794. },
  1795. // multi
  1796. initSelection: function () {
  1797. var data;
  1798. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  1799. this.updateSelection([]);
  1800. this.close();
  1801. // set the placeholder if necessary
  1802. this.clearSearch();
  1803. }
  1804. if (this.select || this.opts.element.val() !== "") {
  1805. var self = this;
  1806. this.opts.initSelection.call(null, this.opts.element, function(data){
  1807. if (data !== undefined && data !== null) {
  1808. self.updateSelection(data);
  1809. self.close();
  1810. // set the placeholder if necessary
  1811. self.clearSearch();
  1812. }
  1813. });
  1814. }
  1815. },
  1816. // multi
  1817. clearSearch: function () {
  1818. var placeholder = this.getPlaceholder();
  1819. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1820. this.search.val(placeholder).addClass("select2-default");
  1821. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1822. this.resizeSearch();
  1823. } else {
  1824. this.search.val("").width(10);
  1825. }
  1826. },
  1827. // multi
  1828. clearPlaceholder: function () {
  1829. if (this.search.hasClass("select2-default")) {
  1830. this.search.val("").removeClass("select2-default");
  1831. }
  1832. },
  1833. // multi
  1834. opening: function () {
  1835. this.parent.opening.apply(this, arguments);
  1836. this.clearPlaceholder();
  1837. this.resizeSearch();
  1838. this.focusSearch();
  1839. this.opts.element.trigger($.Event("open"));
  1840. },
  1841. // multi
  1842. close: function () {
  1843. if (!this.opened()) return;
  1844. this.parent.close.apply(this, arguments);
  1845. },
  1846. // multi
  1847. focus: function () {
  1848. this.close();
  1849. this.search.focus();
  1850. this.opts.element.triggerHandler("focus");
  1851. },
  1852. // multi
  1853. isFocused: function () {
  1854. return this.search.hasClass("select2-focused");
  1855. },
  1856. // multi
  1857. updateSelection: function (data) {
  1858. var ids = [], filtered = [], self = this;
  1859. // filter out duplicates
  1860. $(data).each(function () {
  1861. if (indexOf(self.id(this), ids) < 0) {
  1862. ids.push(self.id(this));
  1863. filtered.push(this);
  1864. }
  1865. });
  1866. data = filtered;
  1867. this.selection.find(".select2-search-choice").remove();
  1868. $(data).each(function () {
  1869. self.addSelectedChoice(this);
  1870. });
  1871. self.postprocessResults();
  1872. },
  1873. tokenize: function() {
  1874. var input = this.search.val();
  1875. input = this.opts.tokenizer(input, this.data(), this.bind(this.onSelect), this.opts);
  1876. if (input != null && input != undefined) {
  1877. this.search.val(input);
  1878. if (input.length > 0) {
  1879. this.open();
  1880. }
  1881. }
  1882. },
  1883. // multi
  1884. onSelect: function (data, options) {
  1885. this.addSelectedChoice(data);
  1886. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  1887. if (this.select || !this.opts.closeOnSelect) this.postprocessResults();
  1888. if (this.opts.closeOnSelect) {
  1889. this.close();
  1890. this.search.width(10);
  1891. } else {
  1892. if (this.countSelectableResults()>0) {
  1893. this.search.width(10);
  1894. this.resizeSearch();
  1895. if (this.val().length >= this.getMaximumSelectionSize()) {
  1896. // if we reached max selection size repaint the results so choices
  1897. // are replaced with the max selection reached message
  1898. this.updateResults(true);
  1899. }
  1900. this.positionDropdown();
  1901. } else {
  1902. // if nothing left to select close
  1903. this.close();
  1904. this.search.width(10);
  1905. }
  1906. }
  1907. // since its not possible to select an element that has already been
  1908. // added we do not need to check if this is a new element before firing change
  1909. this.triggerChange({ added: data });
  1910. if (!options || !options.noFocus)
  1911. this.focusSearch();
  1912. },
  1913. // multi
  1914. cancel: function () {
  1915. this.close();
  1916. this.focusSearch();
  1917. },
  1918. addSelectedChoice: function (data) {
  1919. var enableChoice = !data.locked,
  1920. enabledItem = $(
  1921. "<li class='select2-search-choice'>" +
  1922. " <div></div>" +
  1923. " <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
  1924. "</li>"),
  1925. disabledItem = $(
  1926. "<li class='select2-search-choice select2-locked'>" +
  1927. "<div></div>" +
  1928. "</li>");
  1929. var choice = enableChoice ? enabledItem : disabledItem,
  1930. id = this.id(data),
  1931. val = this.getVal(),
  1932. formatted;
  1933. formatted=this.opts.formatSelection(data, choice.find("div"));
  1934. if (formatted != undefined) {
  1935. choice.find("div").replaceWith("<div>"+this.opts.escapeMarkup(formatted)+"</div>");
  1936. }
  1937. if(enableChoice){
  1938. choice.find(".select2-search-choice-close")
  1939. .bind("mousedown", killEvent)
  1940. .bind("click dblclick", this.bind(function (e) {
  1941. if (!this.enabled) return;
  1942. $(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
  1943. this.unselect($(e.target));
  1944. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1945. this.close();
  1946. this.focusSearch();
  1947. })).dequeue();
  1948. killEvent(e);
  1949. })).bind("focus", this.bind(function () {
  1950. if (!this.enabled) return;
  1951. this.container.addClass("select2-container-active");
  1952. this.dropdown.addClass("select2-drop-active");
  1953. }));
  1954. }
  1955. choice.data("select2-data", data);
  1956. choice.insertBefore(this.searchContainer);
  1957. val.push(id);
  1958. this.setVal(val);
  1959. },
  1960. // multi
  1961. unselect: function (selected) {
  1962. var val = this.getVal(),
  1963. data,
  1964. index;
  1965. selected = selected.closest(".select2-search-choice");
  1966. if (selected.length === 0) {
  1967. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1968. }
  1969. data = selected.data("select2-data");
  1970. if (!data) {
  1971. // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
  1972. // and invoked on an element already removed
  1973. return;
  1974. }
  1975. index = indexOf(this.id(data), val);
  1976. if (index >= 0) {
  1977. val.splice(index, 1);
  1978. this.setVal(val);
  1979. if (this.select) this.postprocessResults();
  1980. }
  1981. selected.remove();
  1982. this.opts.element.trigger({ type: "removed", val: this.id(data), choice: data });
  1983. this.triggerChange({ removed: data });
  1984. },
  1985. // multi
  1986. postprocessResults: function () {
  1987. var val = this.getVal(),
  1988. choices = this.results.find(".select2-result"),
  1989. compound = this.results.find(".select2-result-with-children"),
  1990. self = this;
  1991. choices.each2(function (i, choice) {
  1992. var id = self.id(choice.data("select2-data"));
  1993. if (indexOf(id, val) >= 0) {
  1994. choice.addClass("select2-selected");
  1995. // mark all children of the selected parent as selected
  1996. choice.find(".select2-result-selectable").addClass("select2-selected");
  1997. }
  1998. });
  1999. compound.each2(function(i, choice) {
  2000. // hide an optgroup if it doesnt have any selectable children
  2001. if (!choice.is('.select2-result-selectable')
  2002. && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
  2003. choice.addClass("select2-selected");
  2004. }
  2005. });
  2006. if (this.highlight() == -1){
  2007. self.highlight(0);
  2008. }
  2009. },
  2010. // multi
  2011. resizeSearch: function () {
  2012. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  2013. sideBorderPadding = getSideBorderPadding(this.search);
  2014. minimumWidth = measureTextWidth(this.search) + 10;
  2015. left = this.search.offset().left;
  2016. maxWidth = this.selection.width();
  2017. containerLeft = this.selection.offset().left;
  2018. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  2019. if (searchWidth < minimumWidth) {
  2020. searchWidth = maxWidth - sideBorderPadding;
  2021. }
  2022. if (searchWidth < 40) {
  2023. searchWidth = maxWidth - sideBorderPadding;
  2024. }
  2025. if (searchWidth <= 0) {
  2026. searchWidth = minimumWidth;
  2027. }
  2028. this.search.width(searchWidth);
  2029. },
  2030. // multi
  2031. getVal: function () {
  2032. var val;
  2033. if (this.select) {
  2034. val = this.select.val();
  2035. return val === null ? [] : val;
  2036. } else {
  2037. val = this.opts.element.val();
  2038. return splitVal(val, this.opts.separator);
  2039. }
  2040. },
  2041. // multi
  2042. setVal: function (val) {
  2043. var unique;
  2044. if (this.select) {
  2045. this.select.val(val);
  2046. } else {
  2047. unique = [];
  2048. // filter out duplicates
  2049. $(val).each(function () {
  2050. if (indexOf(this, unique) < 0) unique.push(this);
  2051. });
  2052. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  2053. }
  2054. },
  2055. // multi
  2056. val: function () {
  2057. var val, triggerChange = false, data = [], self=this;
  2058. if (arguments.length === 0) {
  2059. return this.getVal();
  2060. }
  2061. val = arguments[0];
  2062. if (arguments.length > 1) {
  2063. triggerChange = arguments[1];
  2064. }
  2065. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2066. if (!val && val !== 0) {
  2067. this.opts.element.val("");
  2068. this.updateSelection([]);
  2069. this.clearSearch();
  2070. if (triggerChange) {
  2071. this.triggerChange();
  2072. }
  2073. return;
  2074. }
  2075. // val is a list of ids
  2076. this.setVal(val);
  2077. if (this.select) {
  2078. this.opts.initSelection(this.select, this.bind(this.updateSelection));
  2079. if (triggerChange) {
  2080. this.triggerChange();
  2081. }
  2082. } else {
  2083. if (this.opts.initSelection === undefined) {
  2084. throw new Error("val() cannot be called if initSelection() is not defined");
  2085. }
  2086. this.opts.initSelection(this.opts.element, function(data){
  2087. var ids=$(data).map(self.id);
  2088. self.setVal(ids);
  2089. self.updateSelection(data);
  2090. self.clearSearch();
  2091. if (triggerChange) {
  2092. self.triggerChange();
  2093. }
  2094. });
  2095. }
  2096. this.clearSearch();
  2097. },
  2098. // multi
  2099. onSortStart: function() {
  2100. if (this.select) {
  2101. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  2102. }
  2103. // collapse search field into 0 width so its container can be collapsed as well
  2104. this.search.width(0);
  2105. // hide the container
  2106. this.searchContainer.hide();
  2107. },
  2108. // multi
  2109. onSortEnd:function() {
  2110. var val=[], self=this;
  2111. // show search and move it to the end of the list
  2112. this.searchContainer.show();
  2113. // make sure the search container is the last item in the list
  2114. this.searchContainer.appendTo(this.searchContainer.parent());
  2115. // since we collapsed the width in dragStarted, we resize it here
  2116. this.resizeSearch();
  2117. // update selection
  2118. this.selection.find(".select2-search-choice").each(function() {
  2119. val.push(self.opts.id($(this).data("select2-data")));
  2120. });
  2121. this.setVal(val);
  2122. this.triggerChange();
  2123. },
  2124. // multi
  2125. data: function(values) {
  2126. var self=this, ids;
  2127. if (arguments.length === 0) {
  2128. return this.selection
  2129. .find(".select2-search-choice")
  2130. .map(function() { return $(this).data("select2-data"); })
  2131. .get();
  2132. } else {
  2133. if (!values) { values = []; }
  2134. ids = $.map(values, function(e) { return self.opts.id(e); });
  2135. this.setVal(ids);
  2136. this.updateSelection(values);
  2137. this.clearSearch();
  2138. }
  2139. }
  2140. });
  2141. $.fn.select2 = function () {
  2142. var args = Array.prototype.slice.call(arguments, 0),
  2143. opts,
  2144. select2,
  2145. value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
  2146. this.each(function () {
  2147. if (args.length === 0 || typeof(args[0]) === "object") {
  2148. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  2149. opts.element = $(this);
  2150. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2151. multiple = opts.element.attr("multiple");
  2152. } else {
  2153. multiple = opts.multiple || false;
  2154. if ("tags" in opts) {opts.multiple = multiple = true;}
  2155. }
  2156. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  2157. select2.init(opts);
  2158. } else if (typeof(args[0]) === "string") {
  2159. if (indexOf(args[0], allowedMethods) < 0) {
  2160. throw "Unknown method: " + args[0];
  2161. }
  2162. value = undefined;
  2163. select2 = $(this).data("select2");
  2164. if (select2 === undefined) return;
  2165. if (args[0] === "container") {
  2166. value=select2.container;
  2167. } else {
  2168. value = select2[args[0]].apply(select2, args.slice(1));
  2169. }
  2170. if (value !== undefined) {return false;}
  2171. } else {
  2172. throw "Invalid arguments to select2 plugin: " + args;
  2173. }
  2174. });
  2175. return (value === undefined) ? this : value;
  2176. };
  2177. // plugin defaults, accessible to users
  2178. $.fn.select2.defaults = {
  2179. width: "copy",
  2180. loadMorePadding: 0,
  2181. closeOnSelect: true,
  2182. openOnEnter: true,
  2183. containerCss: {},
  2184. dropdownCss: {},
  2185. containerCssClass: "",
  2186. dropdownCssClass: "",
  2187. formatResult: function(result, container, query, escapeMarkup) {
  2188. var markup=[];
  2189. markMatch(result.text, query.term, markup, escapeMarkup);
  2190. return markup.join("");
  2191. },
  2192. formatSelection: function (data, container) {
  2193. return data ? data.text : undefined;
  2194. },
  2195. sortResults: function (results, container, query) {
  2196. return results;
  2197. },
  2198. formatResultCssClass: function(data) {return undefined;},
  2199. formatNoMatches: function () { return "No matches found"; },
  2200. formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); },
  2201. formatInputTooLong: function (input, max) { var n = input.length - max; return "Please enter " + n + " less character" + (n == 1? "" : "s"); },
  2202. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
  2203. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  2204. formatSearching: function () { return "Searching..."; },
  2205. minimumResultsForSearch: 0,
  2206. minimumInputLength: 0,
  2207. maximumInputLength: null,
  2208. maximumSelectionSize: 0,
  2209. id: function (e) { return e.id; },
  2210. matcher: function(term, text) {
  2211. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  2212. },
  2213. separator: ",",
  2214. tokenSeparators: [],
  2215. tokenizer: defaultTokenizer,
  2216. escapeMarkup: function (markup) {
  2217. var replace_map = {
  2218. '\\': '&#92;',
  2219. '&': '&amp;',
  2220. '<': '&lt;',
  2221. '>': '&gt;',
  2222. '"': '&quot;',
  2223. "'": '&apos;',
  2224. "/": '&#47;'
  2225. };
  2226. return String(markup).replace(/[&<>"'/\\]/g, function (match) {
  2227. return replace_map[match[0]];
  2228. });
  2229. },
  2230. blurOnChange: false,
  2231. selectOnBlur: false,
  2232. adaptContainerCssClass: function(c) { return c; },
  2233. adaptDropdownCssClass: function(c) { return null; }
  2234. };
  2235. // exports
  2236. window.Select2 = {
  2237. query: {
  2238. ajax: ajax,
  2239. local: local,
  2240. tags: tags
  2241. }, util: {
  2242. debounce: debounce,
  2243. markMatch: markMatch
  2244. }, "class": {
  2245. "abstract": AbstractSelect2,
  2246. "single": SingleSelect2,
  2247. "multi": MultiSelect2
  2248. }
  2249. };
  2250. }(jQuery));