select2.js 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457
  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 = $("<div></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) {
  239. var match=text.toUpperCase().indexOf(term.toUpperCase()),
  240. tl=term.length;
  241. if (match<0) {
  242. markup.push(text);
  243. return;
  244. }
  245. markup.push(text.substring(0, match));
  246. markup.push("<span class='select2-match'>");
  247. markup.push(text.substring(match, match + tl));
  248. markup.push("</span>");
  249. markup.push(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.call(this, query.term, query.page, query.context);
  282. if( null !== handler) { handler.abort(); }
  283. handler = transport.call(null, {
  284. 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))) {
  345. collection.push(group);
  346. }
  347. } else {
  348. if (query.matcher(t, text(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.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, compound, node, label, innerContainer, formatted;
  615. for (i = 0, l = results.length; i < l; i = i + 1) {
  616. result=results[i];
  617. selectable=id(result) !== undefined;
  618. compound=result.children && result.children.length > 0;
  619. node=$("<li></li>");
  620. node.addClass("select2-results-dept-"+depth);
  621. node.addClass("select2-result");
  622. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  623. if (compound) { node.addClass("select2-result-with-children"); }
  624. node.addClass(self.opts.formatResultCssClass(result));
  625. label=$("<div></div>");
  626. label.addClass("select2-result-label");
  627. formatted=opts.formatResult(result, label, query);
  628. if (formatted!==undefined) {
  629. label.html(self.opts.escapeMarkup(formatted));
  630. }
  631. node.append(label);
  632. if (compound) {
  633. innerContainer=$("<ul></ul>");
  634. innerContainer.addClass("select2-result-sub");
  635. populate(result.children, innerContainer, depth+1);
  636. node.append(innerContainer);
  637. }
  638. node.data("select2-data", result);
  639. container.append(node);
  640. }
  641. };
  642. populate(results, container, 0);
  643. }
  644. }, $.fn.select2.defaults, opts);
  645. if (typeof(opts.id) !== "function") {
  646. idKey = opts.id;
  647. opts.id = function (e) { return e[idKey]; };
  648. }
  649. if (select) {
  650. opts.query = this.bind(function (query) {
  651. var data = { results: [], more: false },
  652. term = query.term,
  653. children, firstChild, process;
  654. process=function(element, collection) {
  655. var group;
  656. if (element.is("option")) {
  657. if (query.matcher(term, element.text(), element)) {
  658. collection.push({id:element.attr("value"), text:element.text(), element: element.get(), css: element.attr("class")});
  659. }
  660. } else if (element.is("optgroup")) {
  661. group={text:element.attr("label"), children:[], element: element.get(), css: element.attr("class")};
  662. element.children().each2(function(i, elm) { process(elm, group.children); });
  663. if (group.children.length>0) {
  664. collection.push(group);
  665. }
  666. }
  667. };
  668. children=element.children();
  669. // ignore the placeholder option if there is one
  670. if (this.getPlaceholder() !== undefined && children.length > 0) {
  671. firstChild = children[0];
  672. if ($(firstChild).text() === "") {
  673. children=children.not(firstChild);
  674. }
  675. }
  676. children.each2(function(i, elm) { process(elm, data.results); });
  677. query.callback(data);
  678. });
  679. // this is needed because inside val() we construct choices from options and there id is hardcoded
  680. opts.id=function(e) { return e.id; };
  681. opts.formatResultCssClass = function(data) { return data.css; }
  682. } else {
  683. if (!("query" in opts)) {
  684. if ("ajax" in opts) {
  685. ajaxUrl = opts.element.data("ajax-url");
  686. if (ajaxUrl && ajaxUrl.length > 0) {
  687. opts.ajax.url = ajaxUrl;
  688. }
  689. opts.query = ajax(opts.ajax);
  690. } else if ("data" in opts) {
  691. opts.query = local(opts.data);
  692. } else if ("tags" in opts) {
  693. opts.query = tags(opts.tags);
  694. if (opts.createSearchChoice === undefined) {
  695. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  696. }
  697. opts.initSelection = function (element, callback) {
  698. var data = [];
  699. $(splitVal(element.val(), opts.separator)).each(function () {
  700. var id = this, text = this, tags=opts.tags;
  701. if ($.isFunction(tags)) tags=tags();
  702. $(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } });
  703. data.push({id: id, text: text});
  704. });
  705. callback(data);
  706. };
  707. }
  708. }
  709. }
  710. if (typeof(opts.query) !== "function") {
  711. throw "query function not defined for Select2 " + opts.element.attr("id");
  712. }
  713. return opts;
  714. },
  715. /**
  716. * Monitor the original element for changes and update select2 accordingly
  717. */
  718. // abstract
  719. monitorSource: function () {
  720. this.opts.element.bind("change.select2", this.bind(function (e) {
  721. if (this.opts.element.data("select2-change-triggered") !== true) {
  722. this.initSelection();
  723. }
  724. }));
  725. },
  726. /**
  727. * Triggers the change event on the source element
  728. */
  729. // abstract
  730. triggerChange: function (details) {
  731. details = details || {};
  732. details= $.extend({}, details, { type: "change", val: this.val() });
  733. // prevents recursive triggering
  734. this.opts.element.data("select2-change-triggered", true);
  735. this.opts.element.trigger(details);
  736. this.opts.element.data("select2-change-triggered", false);
  737. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  738. // so here we trigger the click event manually
  739. this.opts.element.click();
  740. // ValidationEngine ignorea the change event and listens instead to blur
  741. // so here we trigger the blur event manually if so desired
  742. if (this.opts.blurOnChange)
  743. this.opts.element.blur();
  744. },
  745. // abstract
  746. enable: function() {
  747. if (this.enabled) return;
  748. this.enabled=true;
  749. this.container.removeClass("select2-container-disabled");
  750. this.opts.element.removeAttr("disabled");
  751. },
  752. // abstract
  753. disable: function() {
  754. if (!this.enabled) return;
  755. this.close();
  756. this.enabled=false;
  757. this.container.addClass("select2-container-disabled");
  758. this.opts.element.attr("disabled", "disabled");
  759. },
  760. // abstract
  761. opened: function () {
  762. return this.container.hasClass("select2-dropdown-open");
  763. },
  764. // abstract
  765. positionDropdown: function() {
  766. var offset = this.container.offset(),
  767. height = this.container.outerHeight(false),
  768. width = this.container.outerWidth(false),
  769. dropHeight = this.dropdown.outerHeight(false),
  770. viewPortRight = $(window).scrollLeft() + document.documentElement.clientWidth,
  771. viewportBottom = $(window).scrollTop() + document.documentElement.clientHeight,
  772. dropTop = offset.top + height,
  773. dropLeft = offset.left,
  774. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  775. enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
  776. dropWidth = this.dropdown.outerWidth(false),
  777. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
  778. aboveNow = this.dropdown.hasClass("select2-drop-above"),
  779. bodyOffset,
  780. above,
  781. css;
  782. // console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  783. // console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  784. // fix positioning when body has an offset and is not position: static
  785. if (this.body().css('position') !== 'static') {
  786. bodyOffset = this.body().offset();
  787. dropTop -= bodyOffset.top;
  788. dropLeft -= bodyOffset.left;
  789. }
  790. // always prefer the current above/below alignment, unless there is not enough room
  791. if (aboveNow) {
  792. above = true;
  793. if (!enoughRoomAbove && enoughRoomBelow) above = false;
  794. } else {
  795. above = false;
  796. if (!enoughRoomBelow && enoughRoomAbove) above = true;
  797. }
  798. if (!enoughRoomOnRight) {
  799. dropLeft = offset.left + width - dropWidth;
  800. }
  801. if (above) {
  802. dropTop = offset.top - dropHeight;
  803. this.container.addClass("select2-drop-above");
  804. this.dropdown.addClass("select2-drop-above");
  805. }
  806. else {
  807. this.container.removeClass("select2-drop-above");
  808. this.dropdown.removeClass("select2-drop-above");
  809. }
  810. css = $.extend({
  811. top: dropTop,
  812. left: dropLeft,
  813. width: width
  814. }, evaluate(this.opts.dropdownCss));
  815. this.dropdown.css(css);
  816. },
  817. // abstract
  818. shouldOpen: function() {
  819. var event;
  820. if (this.opened()) return false;
  821. event = $.Event("open");
  822. this.opts.element.trigger(event);
  823. return !event.isDefaultPrevented();
  824. },
  825. // abstract
  826. clearDropdownAlignmentPreference: function() {
  827. // clear the classes used to figure out the preference of where the dropdown should be opened
  828. this.container.removeClass("select2-drop-above");
  829. this.dropdown.removeClass("select2-drop-above");
  830. },
  831. /**
  832. * Opens the dropdown
  833. *
  834. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  835. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  836. */
  837. // abstract
  838. open: function () {
  839. if (!this.shouldOpen()) return false;
  840. window.setTimeout(this.bind(this.opening), 1);
  841. return true;
  842. },
  843. /**
  844. * Performs the opening of the dropdown
  845. */
  846. // abstract
  847. opening: function() {
  848. var cid = this.containerId, selector = this.containerSelector,
  849. scroll = "scroll." + cid, resize = "resize." + cid;
  850. this.container.parents().each(function() {
  851. $(this).bind(scroll, function() {
  852. var s2 = $(selector);
  853. if (s2.length == 0) {
  854. $(this).unbind(scroll);
  855. }
  856. s2.select2("close");
  857. });
  858. });
  859. window.setTimeout(function() {
  860. // this is done inside a timeout because IE will sometimes fire a resize event while opening
  861. // the dropdown and that causes this handler to immediately close it. this way the dropdown
  862. // has a chance to fully open before we start listening to resize events
  863. $(window).bind(resize, function() {
  864. var s2 = $(selector);
  865. if (s2.length == 0) {
  866. $(window).unbind(resize);
  867. }
  868. s2.select2("close");
  869. })
  870. }, 10);
  871. this.clearDropdownAlignmentPreference();
  872. if (this.search.val() === " ") { this.search.val(""); }
  873. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  874. this.updateResults(true);
  875. if(this.dropdown[0] !== this.body().children().last()[0]) {
  876. this.dropdown.detach().appendTo(this.body());
  877. }
  878. this.dropdown.show();
  879. this.positionDropdown();
  880. this.dropdown.addClass("select2-drop-active");
  881. this.ensureHighlightVisible();
  882. this.focusSearch();
  883. },
  884. // abstract
  885. close: function () {
  886. if (!this.opened()) return;
  887. var self = this;
  888. this.container.parents().each(function() {
  889. $(this).unbind("scroll." + self.containerId);
  890. });
  891. $(window).unbind("resize." + this.containerId);
  892. this.clearDropdownAlignmentPreference();
  893. this.dropdown.hide();
  894. this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
  895. this.results.empty();
  896. this.clearSearch();
  897. this.opts.element.trigger($.Event("close"));
  898. },
  899. // abstract
  900. clearSearch: function () {
  901. },
  902. // abstract
  903. ensureHighlightVisible: function () {
  904. var results = this.results, children, index, child, hb, rb, y, more;
  905. index = this.highlight();
  906. if (index < 0) return;
  907. if (index == 0) {
  908. // if the first element is highlighted scroll all the way to the top,
  909. // that way any unselectable headers above it will also be scrolled
  910. // into view
  911. results.scrollTop(0);
  912. return;
  913. }
  914. children = results.find(".select2-result-selectable");
  915. child = $(children[index]);
  916. hb = child.offset().top + child.outerHeight(true);
  917. // if this is the last child lets also make sure select2-more-results is visible
  918. if (index === children.length - 1) {
  919. more = results.find("li.select2-more-results");
  920. if (more.length > 0) {
  921. hb = more.offset().top + more.outerHeight(true);
  922. }
  923. }
  924. rb = results.offset().top + results.outerHeight(true);
  925. if (hb > rb) {
  926. results.scrollTop(results.scrollTop() + (hb - rb));
  927. }
  928. y = child.offset().top - results.offset().top;
  929. // make sure the top of the element is visible
  930. if (y < 0 && child.css('display') != 'none' ) {
  931. results.scrollTop(results.scrollTop() + y); // y is negative
  932. }
  933. },
  934. // abstract
  935. moveHighlight: function (delta) {
  936. var choices = this.results.find(".select2-result-selectable"),
  937. index = this.highlight();
  938. while (index > -1 && index < choices.length) {
  939. index += delta;
  940. var choice = $(choices[index]);
  941. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled")) {
  942. this.highlight(index);
  943. break;
  944. }
  945. }
  946. },
  947. // abstract
  948. highlight: function (index) {
  949. var choices = this.results.find(".select2-result-selectable").not(".select2-disabled");
  950. if (arguments.length === 0) {
  951. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  952. }
  953. if (index >= choices.length) index = choices.length - 1;
  954. if (index < 0) index = 0;
  955. choices.removeClass("select2-highlighted");
  956. $(choices[index]).addClass("select2-highlighted");
  957. this.ensureHighlightVisible();
  958. },
  959. // abstract
  960. countSelectableResults: function() {
  961. return this.results.find(".select2-result-selectable").not(".select2-disabled").length;
  962. },
  963. // abstract
  964. highlightUnderEvent: function (event) {
  965. var el = $(event.target).closest(".select2-result-selectable");
  966. if (el.length > 0 && !el.is(".select2-highlighted")) {
  967. var choices = this.results.find('.select2-result-selectable');
  968. this.highlight(choices.index(el));
  969. } else if (el.length == 0) {
  970. // if we are over an unselectable item remove al highlights
  971. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  972. }
  973. },
  974. // abstract
  975. loadMoreIfNeeded: function () {
  976. var results = this.results,
  977. more = results.find("li.select2-more-results"),
  978. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  979. offset = -1, // index of first element without data
  980. page = this.resultsPage + 1,
  981. self=this,
  982. term=this.search.val(),
  983. context=this.context;
  984. if (more.length === 0) return;
  985. below = more.offset().top - results.offset().top - results.height();
  986. if (below <= 0) {
  987. more.addClass("select2-active");
  988. this.opts.query({
  989. term: term,
  990. page: page,
  991. context: context,
  992. matcher: this.opts.matcher,
  993. callback: this.bind(function (data) {
  994. // ignore a response if the select2 has been closed before it was received
  995. if (!self.opened()) return;
  996. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  997. if (data.more===true) {
  998. more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
  999. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1000. } else {
  1001. more.remove();
  1002. }
  1003. self.positionDropdown();
  1004. self.resultsPage = page;
  1005. })});
  1006. }
  1007. },
  1008. /**
  1009. * Default tokenizer function which does nothing
  1010. */
  1011. tokenize: function() {
  1012. },
  1013. /**
  1014. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  1015. */
  1016. // abstract
  1017. updateResults: function (initial) {
  1018. var search = this.search, results = this.results, opts = this.opts, data, self=this, input;
  1019. // if the search is currently hidden we do not alter the results
  1020. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  1021. return;
  1022. }
  1023. search.addClass("select2-active");
  1024. function postRender() {
  1025. results.scrollTop(0);
  1026. search.removeClass("select2-active");
  1027. self.positionDropdown();
  1028. }
  1029. function render(html) {
  1030. results.html(self.opts.escapeMarkup(html));
  1031. postRender();
  1032. }
  1033. if (opts.maximumSelectionSize >=1) {
  1034. data = this.data();
  1035. if ($.isArray(data) && data.length >= opts.maximumSelectionSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  1036. render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(opts.maximumSelectionSize) + "</li>");
  1037. return;
  1038. }
  1039. }
  1040. if (search.val().length < opts.minimumInputLength) {
  1041. if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  1042. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  1043. } else {
  1044. render("");
  1045. }
  1046. return;
  1047. }
  1048. else if (opts.formatSearching()) {
  1049. render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
  1050. }
  1051. if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
  1052. if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
  1053. render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>");
  1054. } else {
  1055. render("");
  1056. }
  1057. return;
  1058. }
  1059. // give the tokenizer a chance to pre-process the input
  1060. input = this.tokenize();
  1061. if (input != undefined && input != null) {
  1062. search.val(input);
  1063. }
  1064. this.resultsPage = 1;
  1065. opts.query({
  1066. term: search.val(),
  1067. page: this.resultsPage,
  1068. context: null,
  1069. matcher: opts.matcher,
  1070. callback: this.bind(function (data) {
  1071. var def; // default choice
  1072. // ignore a response if the select2 has been closed before it was received
  1073. if (!this.opened()) return;
  1074. // save context, if any
  1075. this.context = (data.context===undefined) ? null : data.context;
  1076. // create a default choice and prepend it to the list
  1077. if (this.opts.createSearchChoice && search.val() !== "") {
  1078. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  1079. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  1080. if ($(data.results).filter(
  1081. function () {
  1082. return equal(self.id(this), self.id(def));
  1083. }).length === 0) {
  1084. data.results.unshift(def);
  1085. }
  1086. }
  1087. }
  1088. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  1089. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  1090. return;
  1091. }
  1092. results.empty();
  1093. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  1094. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  1095. results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
  1096. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1097. }
  1098. this.postprocessResults(data, initial);
  1099. postRender();
  1100. })});
  1101. },
  1102. // abstract
  1103. cancel: function () {
  1104. this.close();
  1105. },
  1106. // abstract
  1107. blur: function () {
  1108. this.close();
  1109. this.container.removeClass("select2-container-active");
  1110. this.dropdown.removeClass("select2-drop-active");
  1111. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  1112. if (this.search[0] === document.activeElement) { this.search.blur(); }
  1113. this.clearSearch();
  1114. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1115. this.opts.element.triggerHandler("blur");
  1116. },
  1117. // abstract
  1118. focusSearch: function () {
  1119. // need to do it here as well as in timeout so it works in IE
  1120. this.search.show();
  1121. this.search.focus();
  1122. /* we do this in a timeout so that current event processing can complete before this code is executed.
  1123. this makes sure the search field is focussed even if the current event would blur it */
  1124. window.setTimeout(this.bind(function () {
  1125. // reset the value so IE places the cursor at the end of the input box
  1126. this.search.show();
  1127. this.search.focus();
  1128. this.search.val(this.search.val());
  1129. }), 10);
  1130. },
  1131. // abstract
  1132. selectHighlighted: function () {
  1133. var index=this.highlight(),
  1134. highlighted=this.results.find(".select2-highlighted").not(".select2-disabled"),
  1135. data = highlighted.closest('.select2-result-selectable').data("select2-data");
  1136. if (data) {
  1137. highlighted.addClass("select2-disabled");
  1138. this.highlight(index);
  1139. this.onSelect(data);
  1140. }
  1141. },
  1142. // abstract
  1143. getPlaceholder: function () {
  1144. return this.opts.element.attr("placeholder") ||
  1145. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1146. this.opts.element.data("placeholder") ||
  1147. this.opts.placeholder;
  1148. },
  1149. /**
  1150. * Get the desired width for the container element. This is
  1151. * derived first from option `width` passed to select2, then
  1152. * the inline 'style' on the original element, and finally
  1153. * falls back to the jQuery calculated element width.
  1154. */
  1155. // abstract
  1156. initContainerWidth: function () {
  1157. function resolveContainerWidth() {
  1158. var style, attrs, matches, i, l;
  1159. if (this.opts.width === "off") {
  1160. return null;
  1161. } else if (this.opts.width === "element"){
  1162. return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
  1163. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1164. // check if there is inline style on the element that contains width
  1165. style = this.opts.element.attr('style');
  1166. if (style !== undefined) {
  1167. attrs = style.split(';');
  1168. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1169. matches = attrs[i].replace(/\s/g, '')
  1170. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  1171. if (matches !== null && matches.length >= 1)
  1172. return matches[1];
  1173. }
  1174. }
  1175. if (this.opts.width === "resolve") {
  1176. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1177. // when attached to input type=hidden or elements hidden via css
  1178. style = this.opts.element.css('width');
  1179. if (style.indexOf("%") > 0) return style;
  1180. // finally, fallback on the calculated width of the element
  1181. return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
  1182. }
  1183. return null;
  1184. } else if ($.isFunction(this.opts.width)) {
  1185. return this.opts.width();
  1186. } else {
  1187. return this.opts.width;
  1188. }
  1189. };
  1190. var width = resolveContainerWidth.call(this);
  1191. if (width !== null) {
  1192. this.container.attr("style", "width: "+width);
  1193. }
  1194. }
  1195. });
  1196. SingleSelect2 = clazz(AbstractSelect2, {
  1197. // single
  1198. createContainer: function () {
  1199. var container = $("<div></div>", {
  1200. "class": "select2-container"
  1201. }).html([
  1202. " <a href='javascript:void(0)' onclick='return false;' class='select2-choice'>",
  1203. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  1204. " <div><b></b></div>" ,
  1205. "</a>",
  1206. " <div class='select2-drop select2-offscreen'>" ,
  1207. " <div class='select2-search'>" ,
  1208. " <input type='text' autocomplete='off' class='select2-input'/>" ,
  1209. " </div>" ,
  1210. " <ul class='select2-results'>" ,
  1211. " </ul>" ,
  1212. "</div>"].join(""));
  1213. return container;
  1214. },
  1215. // single
  1216. opening: function () {
  1217. this.search.show();
  1218. this.parent.opening.apply(this, arguments);
  1219. this.dropdown.removeClass("select2-offscreen");
  1220. },
  1221. // single
  1222. close: function () {
  1223. if (!this.opened()) return;
  1224. this.parent.close.apply(this, arguments);
  1225. this.dropdown.removeAttr("style").addClass("select2-offscreen").insertAfter(this.selection).show();
  1226. },
  1227. // single
  1228. focus: function () {
  1229. this.close();
  1230. this.selection.focus();
  1231. },
  1232. // single
  1233. isFocused: function () {
  1234. return this.selection[0] === document.activeElement;
  1235. },
  1236. // single
  1237. cancel: function () {
  1238. this.parent.cancel.apply(this, arguments);
  1239. this.selection.focus();
  1240. },
  1241. // single
  1242. initContainer: function () {
  1243. var selection,
  1244. container = this.container,
  1245. dropdown = this.dropdown,
  1246. clickingInside = false;
  1247. this.selection = selection = container.find(".select2-choice");
  1248. this.search.bind("keydown", this.bind(function (e) {
  1249. if (!this.enabled) return;
  1250. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1251. // prevent the page from scrolling
  1252. killEvent(e);
  1253. return;
  1254. }
  1255. if (this.opened()) {
  1256. switch (e.which) {
  1257. case KEY.UP:
  1258. case KEY.DOWN:
  1259. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1260. killEvent(e);
  1261. return;
  1262. case KEY.TAB:
  1263. case KEY.ENTER:
  1264. this.selectHighlighted();
  1265. killEvent(e);
  1266. return;
  1267. case KEY.ESC:
  1268. this.cancel(e);
  1269. killEvent(e);
  1270. return;
  1271. }
  1272. } else {
  1273. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1274. return;
  1275. }
  1276. if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
  1277. return;
  1278. }
  1279. this.open();
  1280. if (e.which === KEY.ENTER) {
  1281. // do not propagate the event otherwise we open, and propagate enter which closes
  1282. return;
  1283. }
  1284. }
  1285. }));
  1286. this.search.bind("focus", this.bind(function() {
  1287. this.selection.attr("tabIndex", "-1");
  1288. }));
  1289. this.search.bind("blur", this.bind(function() {
  1290. if (!this.opened()) this.container.removeClass("select2-container-active");
  1291. window.setTimeout(this.bind(function() {
  1292. // restore original tab index
  1293. var ti=this.opts.element.attr("tabIndex") || 0;
  1294. if (ti) {
  1295. this.selection.attr("tabIndex", ti);
  1296. } else {
  1297. this.selection.removeAttr("tabIndex");
  1298. }
  1299. }), 10);
  1300. }));
  1301. selection.delegate("abbr", "mousedown", this.bind(function (e) {
  1302. if (!this.enabled) return;
  1303. this.clear();
  1304. killEventImmediately(e);
  1305. this.close();
  1306. this.triggerChange();
  1307. this.selection.focus();
  1308. }));
  1309. selection.bind("mousedown", this.bind(function (e) {
  1310. clickingInside = true;
  1311. if (this.opened()) {
  1312. this.close();
  1313. this.selection.focus();
  1314. } else if (this.enabled) {
  1315. this.open();
  1316. }
  1317. clickingInside = false;
  1318. }));
  1319. dropdown.bind("mousedown", this.bind(function() { this.search.focus(); }));
  1320. selection.bind("focus", this.bind(function() {
  1321. this.container.addClass("select2-container-active");
  1322. // hide the search so the tab key does not focus on it
  1323. this.search.attr("tabIndex", "-1");
  1324. }));
  1325. selection.bind("blur", this.bind(function() {
  1326. if (!this.opened()) {
  1327. this.container.removeClass("select2-container-active");
  1328. }
  1329. window.setTimeout(this.bind(function() { this.search.attr("tabIndex", this.opts.element.attr("tabIndex") || 0); }), 10);
  1330. }));
  1331. selection.bind("keydown", this.bind(function(e) {
  1332. if (!this.enabled) return;
  1333. if (e.which == KEY.DOWN || e.which == KEY.UP
  1334. || (e.which == KEY.ENTER && this.opts.openOnEnter)) {
  1335. this.open();
  1336. killEvent(e);
  1337. return;
  1338. }
  1339. if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
  1340. if (this.opts.allowClear) {
  1341. this.clear();
  1342. }
  1343. killEvent(e);
  1344. return;
  1345. }
  1346. }));
  1347. selection.bind("keypress", this.bind(function(e) {
  1348. var key = String.fromCharCode(e.which);
  1349. this.search.val(key);
  1350. this.open();
  1351. }));
  1352. this.setPlaceholder();
  1353. this.search.bind("focus", this.bind(function() {
  1354. this.container.addClass("select2-container-active");
  1355. }));
  1356. },
  1357. // single
  1358. clear: function() {
  1359. this.opts.element.val("");
  1360. this.selection.find("span").empty();
  1361. this.selection.removeData("select2-data");
  1362. this.setPlaceholder();
  1363. },
  1364. /**
  1365. * Sets selection based on source element's value
  1366. */
  1367. // single
  1368. initSelection: function () {
  1369. var selected;
  1370. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  1371. this.close();
  1372. this.setPlaceholder();
  1373. } else {
  1374. var self = this;
  1375. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1376. if (selected !== undefined && selected !== null) {
  1377. self.updateSelection(selected);
  1378. self.close();
  1379. self.setPlaceholder();
  1380. }
  1381. });
  1382. }
  1383. },
  1384. // single
  1385. prepareOpts: function () {
  1386. var opts = this.parent.prepareOpts.apply(this, arguments);
  1387. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1388. // install the selection initializer
  1389. opts.initSelection = function (element, callback) {
  1390. var selected = element.find(":selected");
  1391. // a single select box always has a value, no need to null check 'selected'
  1392. if ($.isFunction(callback))
  1393. callback({id: selected.attr("value"), text: selected.text(), element:selected});
  1394. };
  1395. }
  1396. return opts;
  1397. },
  1398. // single
  1399. setPlaceholder: function () {
  1400. var placeholder = this.getPlaceholder();
  1401. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1402. // check for a first blank option if attached to a select
  1403. if (this.select && this.select.find("option:first").text() !== "") return;
  1404. this.selection.find("span").html(this.opts.escapeMarkup(placeholder));
  1405. this.selection.addClass("select2-default");
  1406. this.selection.find("abbr").hide();
  1407. }
  1408. },
  1409. // single
  1410. postprocessResults: function (data, initial) {
  1411. var selected = 0, self = this, showSearchInput = true;
  1412. // find the selected element in the result list
  1413. this.results.find(".select2-result-selectable").each2(function (i, elm) {
  1414. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1415. selected = i;
  1416. return false;
  1417. }
  1418. });
  1419. // and highlight it
  1420. this.highlight(selected);
  1421. // hide the search box if this is the first we got the results and there are a few of them
  1422. if (initial === true) {
  1423. showSearchInput = this.showSearchInput = countResults(data.results) >= this.opts.minimumResultsForSearch;
  1424. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1425. //add "select2-with-searchbox" to the container if search box is shown
  1426. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1427. }
  1428. },
  1429. // single
  1430. onSelect: function (data) {
  1431. var old = this.opts.element.val();
  1432. this.opts.element.val(this.id(data));
  1433. this.updateSelection(data);
  1434. this.close();
  1435. this.selection.focus();
  1436. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1437. },
  1438. // single
  1439. updateSelection: function (data) {
  1440. var container=this.selection.find("span"), formatted;
  1441. this.selection.data("select2-data", data);
  1442. container.empty();
  1443. formatted=this.opts.formatSelection(data, container);
  1444. if (formatted !== undefined) {
  1445. container.append(this.opts.escapeMarkup(formatted));
  1446. }
  1447. this.selection.removeClass("select2-default");
  1448. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1449. this.selection.find("abbr").show();
  1450. }
  1451. },
  1452. // single
  1453. val: function () {
  1454. var val, data = null, self = this;
  1455. if (arguments.length === 0) {
  1456. return this.opts.element.val();
  1457. }
  1458. val = arguments[0];
  1459. if (this.select) {
  1460. this.select
  1461. .val(val)
  1462. .find(":selected").each2(function (i, elm) {
  1463. data = {id: elm.attr("value"), text: elm.text()};
  1464. return false;
  1465. });
  1466. this.updateSelection(data);
  1467. this.setPlaceholder();
  1468. this.triggerChange();
  1469. } else {
  1470. if (this.opts.initSelection === undefined) {
  1471. throw new Error("cannot call val() if initSelection() is not defined");
  1472. }
  1473. // val is an id. !val is true for [undefined,null,'']
  1474. if (!val) {
  1475. this.clear();
  1476. this.triggerChange();
  1477. return;
  1478. }
  1479. this.opts.element.val(val);
  1480. this.opts.initSelection(this.opts.element, function(data){
  1481. self.opts.element.val(!data ? "" : self.id(data));
  1482. self.updateSelection(data);
  1483. self.setPlaceholder();
  1484. self.triggerChange();
  1485. });
  1486. }
  1487. },
  1488. // single
  1489. clearSearch: function () {
  1490. this.search.val("");
  1491. },
  1492. // single
  1493. data: function(value) {
  1494. var data;
  1495. if (arguments.length === 0) {
  1496. data = this.selection.data("select2-data");
  1497. if (data == undefined) data = null;
  1498. return data;
  1499. } else {
  1500. if (!value || value === "") {
  1501. this.clear();
  1502. } else {
  1503. this.opts.element.val(!value ? "" : this.id(value));
  1504. this.updateSelection(value);
  1505. }
  1506. }
  1507. }
  1508. });
  1509. MultiSelect2 = clazz(AbstractSelect2, {
  1510. // multi
  1511. createContainer: function () {
  1512. var container = $("<div></div>", {
  1513. "class": "select2-container select2-container-multi"
  1514. }).html([
  1515. " <ul class='select2-choices'>",
  1516. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1517. " <li class='select2-search-field'>" ,
  1518. " <input type='text' autocomplete='off' class='select2-input'>" ,
  1519. " </li>" ,
  1520. "</ul>" ,
  1521. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1522. " <ul class='select2-results'>" ,
  1523. " </ul>" ,
  1524. "</div>"].join(""));
  1525. return container;
  1526. },
  1527. // multi
  1528. prepareOpts: function () {
  1529. var opts = this.parent.prepareOpts.apply(this, arguments);
  1530. // TODO validate placeholder is a string if specified
  1531. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1532. // install sthe selection initializer
  1533. opts.initSelection = function (element,callback) {
  1534. var data = [];
  1535. element.find(":selected").each2(function (i, elm) {
  1536. data.push({id: elm.attr("value"), text: elm.text(), element: elm});
  1537. });
  1538. if ($.isFunction(callback))
  1539. callback(data);
  1540. };
  1541. }
  1542. return opts;
  1543. },
  1544. // multi
  1545. initContainer: function () {
  1546. var selector = ".select2-choices", selection;
  1547. this.searchContainer = this.container.find(".select2-search-field");
  1548. this.selection = selection = this.container.find(selector);
  1549. this.search.bind("keydown", this.bind(function (e) {
  1550. if (!this.enabled) return;
  1551. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1552. this.close();
  1553. var choices,
  1554. selected = selection.find(".select2-search-choice-focus");
  1555. if (selected.length > 0) {
  1556. this.unselect(selected.first());
  1557. this.search.width(10);
  1558. killEvent(e);
  1559. return;
  1560. }
  1561. choices = selection.find(".select2-search-choice:not(.select2-locked)");
  1562. if (choices.length > 0) {
  1563. choices.last().addClass("select2-search-choice-focus");
  1564. }
  1565. } else {
  1566. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1567. }
  1568. if (this.opened()) {
  1569. switch (e.which) {
  1570. case KEY.UP:
  1571. case KEY.DOWN:
  1572. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1573. killEvent(e);
  1574. return;
  1575. case KEY.ENTER:
  1576. case KEY.TAB:
  1577. this.selectHighlighted();
  1578. killEvent(e);
  1579. return;
  1580. case KEY.ESC:
  1581. this.cancel(e);
  1582. killEvent(e);
  1583. return;
  1584. }
  1585. }
  1586. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  1587. || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1588. return;
  1589. }
  1590. if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
  1591. return;
  1592. }
  1593. this.open();
  1594. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1595. // prevent the page from scrolling
  1596. killEvent(e);
  1597. }
  1598. }));
  1599. this.search.bind("keyup", this.bind(this.resizeSearch));
  1600. this.search.bind("blur", this.bind(function(e) {
  1601. this.container.removeClass("select2-container-active");
  1602. this.search.removeClass("select2-focused");
  1603. this.clearSearch();
  1604. e.stopImmediatePropagation();
  1605. }));
  1606. this.container.delegate(selector, "mousedown", this.bind(function (e) {
  1607. if (!this.enabled) return;
  1608. if ($(e.target).closest(".select2-search-choice").length > 0) {
  1609. // clicked inside a select2 search choice, do not open
  1610. return;
  1611. }
  1612. this.clearPlaceholder();
  1613. this.open();
  1614. this.focusSearch();
  1615. e.preventDefault();
  1616. }));
  1617. this.container.delegate(selector, "focus", this.bind(function () {
  1618. if (!this.enabled) return;
  1619. this.container.addClass("select2-container-active");
  1620. this.dropdown.addClass("select2-drop-active");
  1621. this.clearPlaceholder();
  1622. }));
  1623. // set the placeholder if necessary
  1624. this.clearSearch();
  1625. },
  1626. // multi
  1627. enable: function() {
  1628. if (this.enabled) return;
  1629. this.parent.enable.apply(this, arguments);
  1630. this.search.removeAttr("disabled");
  1631. },
  1632. // multi
  1633. disable: function() {
  1634. if (!this.enabled) return;
  1635. this.parent.disable.apply(this, arguments);
  1636. this.search.attr("disabled", true);
  1637. },
  1638. // multi
  1639. initSelection: function () {
  1640. var data;
  1641. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  1642. this.updateSelection([]);
  1643. this.close();
  1644. // set the placeholder if necessary
  1645. this.clearSearch();
  1646. }
  1647. if (this.select || this.opts.element.val() !== "") {
  1648. var self = this;
  1649. this.opts.initSelection.call(null, this.opts.element, function(data){
  1650. if (data !== undefined && data !== null) {
  1651. self.updateSelection(data);
  1652. self.close();
  1653. // set the placeholder if necessary
  1654. self.clearSearch();
  1655. }
  1656. });
  1657. }
  1658. },
  1659. // multi
  1660. clearSearch: function () {
  1661. var placeholder = this.getPlaceholder();
  1662. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1663. this.search.val(placeholder).addClass("select2-default");
  1664. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1665. this.resizeSearch();
  1666. } else {
  1667. // we set this to " " instead of "" and later clear it on focus() because there is a firefox bug
  1668. // that does not properly render the caret when the field starts out blank
  1669. this.search.val(" ").width(10);
  1670. }
  1671. },
  1672. // multi
  1673. clearPlaceholder: function () {
  1674. if (this.search.hasClass("select2-default")) {
  1675. this.search.val("").removeClass("select2-default");
  1676. } else {
  1677. // work around for the space character we set to avoid firefox caret bug
  1678. if (this.search.val() === " ") this.search.val("");
  1679. }
  1680. },
  1681. // multi
  1682. opening: function () {
  1683. this.parent.opening.apply(this, arguments);
  1684. this.clearPlaceholder();
  1685. this.resizeSearch();
  1686. this.focusSearch();
  1687. },
  1688. // multi
  1689. close: function () {
  1690. if (!this.opened()) return;
  1691. this.parent.close.apply(this, arguments);
  1692. },
  1693. // multi
  1694. focus: function () {
  1695. this.close();
  1696. this.search.focus();
  1697. },
  1698. // multi
  1699. isFocused: function () {
  1700. return this.search.hasClass("select2-focused");
  1701. },
  1702. // multi
  1703. updateSelection: function (data) {
  1704. var ids = [], filtered = [], self = this;
  1705. // filter out duplicates
  1706. $(data).each(function () {
  1707. if (indexOf(self.id(this), ids) < 0) {
  1708. ids.push(self.id(this));
  1709. filtered.push(this);
  1710. }
  1711. });
  1712. data = filtered;
  1713. this.selection.find(".select2-search-choice").remove();
  1714. $(data).each(function () {
  1715. self.addSelectedChoice(this);
  1716. });
  1717. self.postprocessResults();
  1718. },
  1719. tokenize: function() {
  1720. var input = this.search.val();
  1721. input = this.opts.tokenizer(input, this.data(), this.bind(this.onSelect), this.opts);
  1722. if (input != null && input != undefined) {
  1723. this.search.val(input);
  1724. if (input.length > 0) {
  1725. this.open();
  1726. }
  1727. }
  1728. },
  1729. // multi
  1730. onSelect: function (data) {
  1731. this.addSelectedChoice(data);
  1732. if (this.select || !this.opts.closeOnSelect) this.postprocessResults();
  1733. if (this.opts.closeOnSelect) {
  1734. this.close();
  1735. this.search.width(10);
  1736. } else {
  1737. if (this.countSelectableResults()>0) {
  1738. this.search.width(10);
  1739. this.resizeSearch();
  1740. this.positionDropdown();
  1741. } else {
  1742. // if nothing left to select close
  1743. this.close();
  1744. }
  1745. }
  1746. // since its not possible to select an element that has already been
  1747. // added we do not need to check if this is a new element before firing change
  1748. this.triggerChange({ added: data });
  1749. this.focusSearch();
  1750. },
  1751. // multi
  1752. cancel: function () {
  1753. this.close();
  1754. this.focusSearch();
  1755. },
  1756. addSelectedChoice: function (data) {
  1757. var enableChoice = !data.locked,
  1758. enabledItem = $(
  1759. "<li class='select2-search-choice'>" +
  1760. " <div></div>" +
  1761. " <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
  1762. "</li>"),
  1763. disabledItem = $(
  1764. "<li class='select2-search-choice select2-locked'>" +
  1765. "<div></div>" +
  1766. "</li>");
  1767. var choice = enableChoice ? enabledItem : disabledItem,
  1768. id = this.id(data),
  1769. val = this.getVal(),
  1770. formatted;
  1771. formatted=this.opts.formatSelection(data, choice.find("div"));
  1772. if (formatted != undefined) {
  1773. choice.find("div").replaceWith("<div>"+this.opts.escapeMarkup(formatted)+"</div>");
  1774. }
  1775. if(enableChoice){
  1776. choice.find(".select2-search-choice-close")
  1777. .bind("mousedown", killEvent)
  1778. .bind("click dblclick", this.bind(function (e) {
  1779. if (!this.enabled) return;
  1780. $(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
  1781. this.unselect($(e.target));
  1782. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1783. this.close();
  1784. this.focusSearch();
  1785. })).dequeue();
  1786. killEvent(e);
  1787. })).bind("focus", this.bind(function () {
  1788. if (!this.enabled) return;
  1789. this.container.addClass("select2-container-active");
  1790. this.dropdown.addClass("select2-drop-active");
  1791. }));
  1792. }
  1793. choice.data("select2-data", data);
  1794. choice.insertBefore(this.searchContainer);
  1795. val.push(id);
  1796. this.setVal(val);
  1797. },
  1798. // multi
  1799. unselect: function (selected) {
  1800. var val = this.getVal(),
  1801. data,
  1802. index;
  1803. selected = selected.closest(".select2-search-choice");
  1804. if (selected.length === 0) {
  1805. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1806. }
  1807. data = selected.data("select2-data");
  1808. index = indexOf(this.id(data), val);
  1809. if (index >= 0) {
  1810. val.splice(index, 1);
  1811. this.setVal(val);
  1812. if (this.select) this.postprocessResults();
  1813. }
  1814. selected.remove();
  1815. this.triggerChange({ removed: data });
  1816. },
  1817. // multi
  1818. postprocessResults: function () {
  1819. var val = this.getVal(),
  1820. choices = this.results.find(".select2-result-selectable"),
  1821. compound = this.results.find(".select2-result-with-children"),
  1822. self = this;
  1823. choices.each2(function (i, choice) {
  1824. var id = self.id(choice.data("select2-data"));
  1825. if (indexOf(id, val) >= 0) {
  1826. choice.addClass("select2-disabled").removeClass("select2-result-selectable");
  1827. } else {
  1828. choice.removeClass("select2-disabled").addClass("select2-result-selectable");
  1829. }
  1830. });
  1831. compound.each2(function(i, e) {
  1832. if (!e.is('.select2-result-selectable') && e.find(".select2-result-selectable").length==0) { // FIX FOR HIRECHAL DATA
  1833. e.addClass("select2-disabled");
  1834. } else {
  1835. e.removeClass("select2-disabled");
  1836. }
  1837. });
  1838. if (this.highlight() == -1){
  1839. choices.each2(function (i, choice) {
  1840. if (!choice.hasClass("select2-disabled") && choice.hasClass("select2-result-selectable")) {
  1841. self.highlight(0);
  1842. return false;
  1843. }
  1844. });
  1845. }
  1846. },
  1847. // multi
  1848. resizeSearch: function () {
  1849. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  1850. sideBorderPadding = getSideBorderPadding(this.search);
  1851. minimumWidth = measureTextWidth(this.search) + 10;
  1852. left = this.search.offset().left;
  1853. maxWidth = this.selection.width();
  1854. containerLeft = this.selection.offset().left;
  1855. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  1856. if (searchWidth < minimumWidth) {
  1857. searchWidth = maxWidth - sideBorderPadding;
  1858. }
  1859. if (searchWidth < 40) {
  1860. searchWidth = maxWidth - sideBorderPadding;
  1861. }
  1862. if (searchWidth <= 0) {
  1863. searchWidth = minimumWidth
  1864. }
  1865. this.search.width(searchWidth);
  1866. },
  1867. // multi
  1868. getVal: function () {
  1869. var val;
  1870. if (this.select) {
  1871. val = this.select.val();
  1872. return val === null ? [] : val;
  1873. } else {
  1874. val = this.opts.element.val();
  1875. return splitVal(val, this.opts.separator);
  1876. }
  1877. },
  1878. // multi
  1879. setVal: function (val) {
  1880. var unique;
  1881. if (this.select) {
  1882. this.select.val(val);
  1883. } else {
  1884. unique = [];
  1885. // filter out duplicates
  1886. $(val).each(function () {
  1887. if (indexOf(this, unique) < 0) unique.push(this);
  1888. });
  1889. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  1890. }
  1891. },
  1892. // multi
  1893. val: function () {
  1894. var val, data = [], self=this;
  1895. if (arguments.length === 0) {
  1896. return this.getVal();
  1897. }
  1898. val = arguments[0];
  1899. if (!val) {
  1900. this.opts.element.val("");
  1901. this.updateSelection([]);
  1902. this.clearSearch();
  1903. this.triggerChange();
  1904. return;
  1905. }
  1906. // val is a list of ids
  1907. this.setVal(val);
  1908. if (this.select) {
  1909. this.select.find(":selected").each(function () {
  1910. data.push({id: $(this).attr("value"), text: $(this).text()});
  1911. });
  1912. this.updateSelection(data);
  1913. this.triggerChange();
  1914. } else {
  1915. if (this.opts.initSelection === undefined) {
  1916. throw new Error("val() cannot be called if initSelection() is not defined")
  1917. }
  1918. this.opts.initSelection(this.opts.element, function(data){
  1919. var ids=$(data).map(self.id);
  1920. self.setVal(ids);
  1921. self.updateSelection(data);
  1922. self.clearSearch();
  1923. self.triggerChange();
  1924. });
  1925. }
  1926. this.clearSearch();
  1927. },
  1928. // multi
  1929. onSortStart: function() {
  1930. if (this.select) {
  1931. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  1932. }
  1933. // collapse search field into 0 width so its container can be collapsed as well
  1934. this.search.width(0);
  1935. // hide the container
  1936. this.searchContainer.hide();
  1937. },
  1938. // multi
  1939. onSortEnd:function() {
  1940. var val=[], self=this;
  1941. // show search and move it to the end of the list
  1942. this.searchContainer.show();
  1943. // make sure the search container is the last item in the list
  1944. this.searchContainer.appendTo(this.searchContainer.parent());
  1945. // since we collapsed the width in dragStarted, we resize it here
  1946. this.resizeSearch();
  1947. // update selection
  1948. this.selection.find(".select2-search-choice").each(function() {
  1949. val.push(self.opts.id($(this).data("select2-data")));
  1950. });
  1951. this.setVal(val);
  1952. this.triggerChange();
  1953. },
  1954. // multi
  1955. data: function(values) {
  1956. var self=this, ids;
  1957. if (arguments.length === 0) {
  1958. return this.selection
  1959. .find(".select2-search-choice")
  1960. .map(function() { return $(this).data("select2-data"); })
  1961. .get();
  1962. } else {
  1963. if (!values) { values = []; }
  1964. ids = $.map(values, function(e) { return self.opts.id(e)});
  1965. this.setVal(ids);
  1966. this.updateSelection(values);
  1967. this.clearSearch();
  1968. }
  1969. }
  1970. });
  1971. $.fn.select2 = function () {
  1972. var args = Array.prototype.slice.call(arguments, 0),
  1973. opts,
  1974. select2,
  1975. value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
  1976. this.each(function () {
  1977. if (args.length === 0 || typeof(args[0]) === "object") {
  1978. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1979. opts.element = $(this);
  1980. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1981. multiple = opts.element.attr("multiple");
  1982. } else {
  1983. multiple = opts.multiple || false;
  1984. if ("tags" in opts) {opts.multiple = multiple = true;}
  1985. }
  1986. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1987. select2.init(opts);
  1988. } else if (typeof(args[0]) === "string") {
  1989. if (indexOf(args[0], allowedMethods) < 0) {
  1990. throw "Unknown method: " + args[0];
  1991. }
  1992. value = undefined;
  1993. select2 = $(this).data("select2");
  1994. if (select2 === undefined) return;
  1995. if (args[0] === "container") {
  1996. value=select2.container;
  1997. } else {
  1998. value = select2[args[0]].apply(select2, args.slice(1));
  1999. }
  2000. if (value !== undefined) {return false;}
  2001. } else {
  2002. throw "Invalid arguments to select2 plugin: " + args;
  2003. }
  2004. });
  2005. return (value === undefined) ? this : value;
  2006. };
  2007. // plugin defaults, accessible to users
  2008. $.fn.select2.defaults = {
  2009. width: "copy",
  2010. closeOnSelect: true,
  2011. openOnEnter: true,
  2012. containerCss: {},
  2013. dropdownCss: {},
  2014. containerCssClass: "",
  2015. dropdownCssClass: "",
  2016. formatResult: function(result, container, query) {
  2017. var markup=[];
  2018. markMatch(result.text, query.term, markup);
  2019. return markup.join("");
  2020. },
  2021. formatSelection: function (data, container) {
  2022. return data ? data.text : undefined;
  2023. },
  2024. formatResultCssClass: function(data) {return undefined;},
  2025. formatNoMatches: function () { return "No matches found"; },
  2026. formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); },
  2027. formatInputTooLong: function (input, max) { var n = input.length - max; return "Please enter " + n + " less character" + (n == 1? "" : "s"); },
  2028. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
  2029. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  2030. formatSearching: function () { return "Searching..."; },
  2031. minimumResultsForSearch: 0,
  2032. minimumInputLength: 0,
  2033. maximumInputLength: null,
  2034. maximumSelectionSize: 0,
  2035. id: function (e) { return e.id; },
  2036. matcher: function(term, text) {
  2037. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  2038. },
  2039. separator: ",",
  2040. tokenSeparators: [],
  2041. tokenizer: defaultTokenizer,
  2042. escapeMarkup: function (markup) {
  2043. if (markup && typeof(markup) === "string") {
  2044. return markup.replace(/&/g, "&amp;");
  2045. }
  2046. return markup;
  2047. },
  2048. blurOnChange: false
  2049. };
  2050. // exports
  2051. window.Select2 = {
  2052. query: {
  2053. ajax: ajax,
  2054. local: local,
  2055. tags: tags
  2056. }, util: {
  2057. debounce: debounce,
  2058. markMatch: markMatch
  2059. }, "class": {
  2060. "abstract": AbstractSelect2,
  2061. "single": SingleSelect2,
  2062. "multi": MultiSelect2
  2063. }
  2064. };
  2065. }(jQuery));