select2.js 93 KB

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