select2.js 88 KB

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