select2.js 92 KB

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