1
0

select2.js 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137
  1. /*
  2. Copyright 2012 Igor Vaynberg
  3. Version: 3.4.1 Timestamp: Thu Jun 27 18:02:10 PDT 2013
  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={x:0,y:0}, $document, scrollBarDimensions,
  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. MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>";
  89. $document = $(document);
  90. nextUid=(function() { var counter=1; return function() { return counter++; }; }());
  91. function indexOf(value, array) {
  92. var i = 0, l = array.length;
  93. for (; i < l; i = i + 1) {
  94. if (equal(value, array[i])) return i;
  95. }
  96. return -1;
  97. }
  98. function measureScrollbar () {
  99. var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
  100. $template.appendTo('body');
  101. var dim = {
  102. width: $template.width() - $template[0].clientWidth,
  103. height: $template.height() - $template[0].clientHeight
  104. };
  105. $template.remove();
  106. return dim;
  107. }
  108. /**
  109. * Compares equality of a and b
  110. * @param a
  111. * @param b
  112. */
  113. function equal(a, b) {
  114. if (a === b) return true;
  115. if (a === undefined || b === undefined) return false;
  116. if (a === null || b === null) return false;
  117. // Check whether 'a' or 'b' is a string (primitive or object).
  118. // The concatenation of an empty string (+'') converts its argument to a string's primitive.
  119. if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object
  120. if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object
  121. return false;
  122. }
  123. /**
  124. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  125. * strings
  126. * @param string
  127. * @param separator
  128. */
  129. function splitVal(string, separator) {
  130. var val, i, l;
  131. if (string === null || string.length < 1) return [];
  132. val = string.split(separator);
  133. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  134. return val;
  135. }
  136. function getSideBorderPadding(element) {
  137. return element.outerWidth(false) - element.width();
  138. }
  139. function installKeyUpChangeEvent(element) {
  140. var key="keyup-change-value";
  141. element.on("keydown", function () {
  142. if ($.data(element, key) === undefined) {
  143. $.data(element, key, element.val());
  144. }
  145. });
  146. element.on("keyup", function () {
  147. var val= $.data(element, key);
  148. if (val !== undefined && element.val() !== val) {
  149. $.removeData(element, key);
  150. element.trigger("keyup-change");
  151. }
  152. });
  153. }
  154. $document.on("mousemove", function (e) {
  155. lastMousePosition.x = e.pageX;
  156. lastMousePosition.y = e.pageY;
  157. });
  158. /**
  159. * filters mouse events so an event is fired only if the mouse moved.
  160. *
  161. * filters out mouse events that occur when mouse is stationary but
  162. * the elements under the pointer are scrolled.
  163. */
  164. function installFilteredMouseMove(element) {
  165. element.on("mousemove", function (e) {
  166. var lastpos = lastMousePosition;
  167. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  168. $(e.target).trigger("mousemove-filtered", e);
  169. }
  170. });
  171. }
  172. /**
  173. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  174. * within the last quietMillis milliseconds.
  175. *
  176. * @param quietMillis number of milliseconds to wait before invoking fn
  177. * @param fn function to be debounced
  178. * @param ctx object to be used as this reference within fn
  179. * @return debounced version of fn
  180. */
  181. function debounce(quietMillis, fn, ctx) {
  182. ctx = ctx || undefined;
  183. var timeout;
  184. return function () {
  185. var args = arguments;
  186. window.clearTimeout(timeout);
  187. timeout = window.setTimeout(function() {
  188. fn.apply(ctx, args);
  189. }, quietMillis);
  190. };
  191. }
  192. /**
  193. * A simple implementation of a thunk
  194. * @param formula function used to lazily initialize the thunk
  195. * @return {Function}
  196. */
  197. function thunk(formula) {
  198. var evaluated = false,
  199. value;
  200. return function() {
  201. if (evaluated === false) { value = formula(); evaluated = true; }
  202. return value;
  203. };
  204. };
  205. function installDebouncedScroll(threshold, element) {
  206. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  207. element.on("scroll", function (e) {
  208. if (indexOf(e.target, element.get()) >= 0) notify(e);
  209. });
  210. }
  211. function focus($el) {
  212. if ($el[0] === document.activeElement) return;
  213. /* set the focus in a 0 timeout - that way the focus is set after the processing
  214. of the current event has finished - which seems like the only reliable way
  215. to set focus */
  216. window.setTimeout(function() {
  217. var el=$el[0], pos=$el.val().length, range;
  218. $el.focus();
  219. /* make sure el received focus so we do not error out when trying to manipulate the caret.
  220. sometimes modals or others listeners may steal it after its set */
  221. if ($el.is(":visible") && el === document.activeElement) {
  222. /* after the focus is set move the caret to the end, necessary when we val()
  223. just before setting focus */
  224. if(el.setSelectionRange)
  225. {
  226. el.setSelectionRange(pos, pos);
  227. }
  228. else if (el.createTextRange) {
  229. range = el.createTextRange();
  230. range.collapse(false);
  231. range.select();
  232. }
  233. }
  234. }, 0);
  235. }
  236. function getCursorInfo(el) {
  237. el = $(el)[0];
  238. var offset = 0;
  239. var length = 0;
  240. if ('selectionStart' in el) {
  241. offset = el.selectionStart;
  242. length = el.selectionEnd - offset;
  243. } else if ('selection' in document) {
  244. el.focus();
  245. var sel = document.selection.createRange();
  246. length = document.selection.createRange().text.length;
  247. sel.moveStart('character', -el.value.length);
  248. offset = sel.text.length - length;
  249. }
  250. return { offset: offset, length: length };
  251. }
  252. function killEvent(event) {
  253. event.preventDefault();
  254. event.stopPropagation();
  255. }
  256. function killEventImmediately(event) {
  257. event.preventDefault();
  258. event.stopImmediatePropagation();
  259. }
  260. function measureTextWidth(e) {
  261. if (!sizer){
  262. var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
  263. sizer = $(document.createElement("div")).css({
  264. position: "absolute",
  265. left: "-10000px",
  266. top: "-10000px",
  267. display: "none",
  268. fontSize: style.fontSize,
  269. fontFamily: style.fontFamily,
  270. fontStyle: style.fontStyle,
  271. fontWeight: style.fontWeight,
  272. letterSpacing: style.letterSpacing,
  273. textTransform: style.textTransform,
  274. whiteSpace: "nowrap"
  275. });
  276. sizer.attr("class","select2-sizer");
  277. $("body").append(sizer);
  278. }
  279. sizer.text(e.val());
  280. return sizer.width();
  281. }
  282. function syncCssClasses(dest, src, adapter) {
  283. var classes, replacements = [], adapted;
  284. classes = dest.attr("class");
  285. if (classes) {
  286. classes = '' + classes; // for IE which returns object
  287. $(classes.split(" ")).each2(function() {
  288. if (this.indexOf("select2-") === 0) {
  289. replacements.push(this);
  290. }
  291. });
  292. }
  293. classes = src.attr("class");
  294. if (classes) {
  295. classes = '' + classes; // for IE which returns object
  296. $(classes.split(" ")).each2(function() {
  297. if (this.indexOf("select2-") !== 0) {
  298. adapted = adapter(this);
  299. if (adapted) {
  300. replacements.push(this);
  301. }
  302. }
  303. });
  304. }
  305. dest.attr("class", replacements.join(" "));
  306. }
  307. function markMatch(text, term, markup, escapeMarkup) {
  308. var match=text.toUpperCase().indexOf(term.toUpperCase()),
  309. tl=term.length;
  310. if (match<0) {
  311. markup.push(escapeMarkup(text));
  312. return;
  313. }
  314. markup.push(escapeMarkup(text.substring(0, match)));
  315. markup.push("<span class='select2-match'>");
  316. markup.push(escapeMarkup(text.substring(match, match + tl)));
  317. markup.push("</span>");
  318. markup.push(escapeMarkup(text.substring(match + tl, text.length)));
  319. }
  320. function defaultEscapeMarkup(markup) {
  321. var replace_map = {
  322. '\\': '&#92;',
  323. '&': '&amp;',
  324. '<': '&lt;',
  325. '>': '&gt;',
  326. '"': '&quot;',
  327. "'": '&#39;',
  328. "/": '&#47;'
  329. };
  330. return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
  331. return replace_map[match];
  332. });
  333. }
  334. /**
  335. * Produces an ajax-based query function
  336. *
  337. * @param options object containing configuration paramters
  338. * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax
  339. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  340. * @param options.url url for the data
  341. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  342. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
  343. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  344. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  345. * The expected format is an object containing the following keys:
  346. * results array of objects that will be used as choices
  347. * more (optional) boolean indicating whether there are more results available
  348. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  349. */
  350. function ajax(options) {
  351. var timeout, // current scheduled but not yet executed request
  352. requestSequence = 0, // sequence used to drop out-of-order responses
  353. handler = null,
  354. quietMillis = options.quietMillis || 100,
  355. ajaxUrl = options.url,
  356. self = this;
  357. return function (query) {
  358. window.clearTimeout(timeout);
  359. timeout = window.setTimeout(function () {
  360. requestSequence += 1; // increment the sequence
  361. var requestNumber = requestSequence, // this request's sequence number
  362. data = options.data, // ajax data function
  363. url = ajaxUrl, // ajax url string or function
  364. transport = options.transport || $.fn.select2.ajaxDefaults.transport,
  365. // deprecated - to be removed in 4.0 - use params instead
  366. deprecated = {
  367. type: options.type || 'GET', // set type of request (GET or POST)
  368. cache: options.cache || false,
  369. jsonpCallback: options.jsonpCallback||undefined,
  370. dataType: options.dataType||"json"
  371. },
  372. params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
  373. data = data ? data.call(self, query.term, query.page, query.context) : null;
  374. url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
  375. if (handler) { handler.abort(); }
  376. if (options.params) {
  377. if ($.isFunction(options.params)) {
  378. $.extend(params, options.params.call(self));
  379. } else {
  380. $.extend(params, options.params);
  381. }
  382. }
  383. $.extend(params, {
  384. url: url,
  385. dataType: options.dataType,
  386. data: data,
  387. success: function (data) {
  388. if (requestNumber < requestSequence) {
  389. return;
  390. }
  391. // TODO - replace query.page with query so users have access to term, page, etc.
  392. var results = options.results(data, query.page);
  393. query.callback(results);
  394. }
  395. });
  396. handler = transport.call(self, params);
  397. }, quietMillis);
  398. };
  399. }
  400. /**
  401. * Produces a query function that works with a local array
  402. *
  403. * @param options object containing configuration parameters. The options parameter can either be an array or an
  404. * object.
  405. *
  406. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  407. *
  408. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  409. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  410. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  411. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  412. * the text.
  413. */
  414. function local(options) {
  415. var data = options, // data elements
  416. dataText,
  417. tmp,
  418. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  419. if ($.isArray(data)) {
  420. tmp = data;
  421. data = { results: tmp };
  422. }
  423. if ($.isFunction(data) === false) {
  424. tmp = data;
  425. data = function() { return tmp; };
  426. }
  427. var dataItem = data();
  428. if (dataItem.text) {
  429. text = dataItem.text;
  430. // if text is not a function we assume it to be a key name
  431. if (!$.isFunction(text)) {
  432. dataText = dataItem.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
  433. text = function (item) { return item[dataText]; };
  434. }
  435. }
  436. return function (query) {
  437. var t = query.term, filtered = { results: [] }, process;
  438. if (t === "") {
  439. query.callback(data());
  440. return;
  441. }
  442. process = function(datum, collection) {
  443. var group, attr;
  444. datum = datum[0];
  445. if (datum.children) {
  446. group = {};
  447. for (attr in datum) {
  448. if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
  449. }
  450. group.children=[];
  451. $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
  452. if (group.children.length || query.matcher(t, text(group), datum)) {
  453. collection.push(group);
  454. }
  455. } else {
  456. if (query.matcher(t, text(datum), datum)) {
  457. collection.push(datum);
  458. }
  459. }
  460. };
  461. $(data().results).each2(function(i, datum) { process(datum, filtered.results); });
  462. query.callback(filtered);
  463. };
  464. }
  465. // TODO javadoc
  466. function tags(data) {
  467. var isFunc = $.isFunction(data);
  468. return function (query) {
  469. var t = query.term, filtered = {results: []};
  470. $(isFunc ? data() : data).each(function () {
  471. var isObject = this.text !== undefined,
  472. text = isObject ? this.text : this;
  473. if (t === "" || query.matcher(t, text)) {
  474. filtered.results.push(isObject ? this : {id: this, text: this});
  475. }
  476. });
  477. query.callback(filtered);
  478. };
  479. }
  480. /**
  481. * Checks if the formatter function should be used.
  482. *
  483. * Throws an error if it is not a function. Returns true if it should be used,
  484. * false if no formatting should be performed.
  485. *
  486. * @param formatter
  487. */
  488. function checkFormatter(formatter, formatterName) {
  489. if ($.isFunction(formatter)) return true;
  490. if (!formatter) return false;
  491. throw new Error(formatterName +" must be a function or a falsy value");
  492. }
  493. function evaluate(val) {
  494. return $.isFunction(val) ? val() : val;
  495. }
  496. function countResults(results) {
  497. var count = 0;
  498. $.each(results, function(i, item) {
  499. if (item.children) {
  500. count += countResults(item.children);
  501. } else {
  502. count++;
  503. }
  504. });
  505. return count;
  506. }
  507. /**
  508. * Default tokenizer. This function uses breaks the input on substring match of any string from the
  509. * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
  510. * two options have to be defined in order for the tokenizer to work.
  511. *
  512. * @param input text user has typed so far or pasted into the search field
  513. * @param selection currently selected choices
  514. * @param selectCallback function(choice) callback tho add the choice to selection
  515. * @param opts select2's opts
  516. * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
  517. */
  518. function defaultTokenizer(input, selection, selectCallback, opts) {
  519. var original = input, // store the original so we can compare and know if we need to tell the search to update its text
  520. dupe = false, // check for whether a token we extracted represents a duplicate selected choice
  521. token, // token
  522. index, // position at which the separator was found
  523. i, l, // looping variables
  524. separator; // the matched separator
  525. if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
  526. while (true) {
  527. index = -1;
  528. for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
  529. separator = opts.tokenSeparators[i];
  530. index = input.indexOf(separator);
  531. if (index >= 0) break;
  532. }
  533. if (index < 0) break; // did not find any token separator in the input string, bail
  534. token = input.substring(0, index);
  535. input = input.substring(index + separator.length);
  536. if (token.length > 0) {
  537. token = opts.createSearchChoice.call(this, token, selection);
  538. if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
  539. dupe = false;
  540. for (i = 0, l = selection.length; i < l; i++) {
  541. if (equal(opts.id(token), opts.id(selection[i]))) {
  542. dupe = true; break;
  543. }
  544. }
  545. if (!dupe) selectCallback(token);
  546. }
  547. }
  548. }
  549. if (original!==input) return input;
  550. }
  551. /**
  552. * Creates a new class
  553. *
  554. * @param superClass
  555. * @param methods
  556. */
  557. function clazz(SuperClass, methods) {
  558. var constructor = function () {};
  559. constructor.prototype = new SuperClass;
  560. constructor.prototype.constructor = constructor;
  561. constructor.prototype.parent = SuperClass.prototype;
  562. constructor.prototype = $.extend(constructor.prototype, methods);
  563. return constructor;
  564. }
  565. AbstractSelect2 = clazz(Object, {
  566. // abstract
  567. bind: function (func) {
  568. var self = this;
  569. return function () {
  570. func.apply(self, arguments);
  571. };
  572. },
  573. // abstract
  574. init: function (opts) {
  575. var results, search, resultsSelector = ".select2-results", disabled, readonly;
  576. // prepare options
  577. this.opts = opts = this.prepareOpts(opts);
  578. this.id=opts.id;
  579. // destroy if called on an existing component
  580. if (opts.element.data("select2") !== undefined &&
  581. opts.element.data("select2") !== null) {
  582. opts.element.data("select2").destroy();
  583. }
  584. this.container = this.createContainer();
  585. this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
  586. this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
  587. this.container.attr("id", this.containerId);
  588. // cache the body so future lookups are cheap
  589. this.body = thunk(function() { return opts.element.closest("body"); });
  590. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  591. this.container.css(evaluate(opts.containerCss));
  592. this.container.addClass(evaluate(opts.containerCssClass));
  593. this.elementTabIndex = this.opts.element.attr("tabindex");
  594. // swap container for the element
  595. this.opts.element
  596. .data("select2", this)
  597. .attr("tabindex", "-1")
  598. .before(this.container);
  599. this.container.data("select2", this);
  600. this.dropdown = this.container.find(".select2-drop");
  601. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  602. this.dropdown.data("select2", this);
  603. this.results = results = this.container.find(resultsSelector);
  604. this.search = search = this.container.find("input.select2-input");
  605. this.resultsPage = 0;
  606. this.context = null;
  607. // initialize the container
  608. this.initContainer();
  609. installFilteredMouseMove(this.results);
  610. this.dropdown.on("mousemove-filtered touchstart touchmove touchend", resultsSelector, this.bind(this.highlightUnderEvent));
  611. installDebouncedScroll(80, this.results);
  612. this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));
  613. // do not propagate change event from the search field out of the component
  614. $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
  615. $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});
  616. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  617. if ($.fn.mousewheel) {
  618. results.mousewheel(function (e, delta, deltaX, deltaY) {
  619. var top = results.scrollTop(), height;
  620. if (deltaY > 0 && top - deltaY <= 0) {
  621. results.scrollTop(0);
  622. killEvent(e);
  623. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  624. results.scrollTop(results.get(0).scrollHeight - results.height());
  625. killEvent(e);
  626. }
  627. });
  628. }
  629. installKeyUpChangeEvent(search);
  630. search.on("keyup-change input paste", this.bind(this.updateResults));
  631. search.on("focus", function () { search.addClass("select2-focused"); });
  632. search.on("blur", function () { search.removeClass("select2-focused");});
  633. this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
  634. if ($(e.target).closest(".select2-result-selectable").length > 0) {
  635. this.highlightUnderEvent(e);
  636. this.selectHighlighted(e);
  637. }
  638. }));
  639. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  640. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  641. // dom it will trigger the popup close, which is not what we want
  642. this.dropdown.on("click mouseup mousedown", function (e) { e.stopPropagation(); });
  643. if ($.isFunction(this.opts.initSelection)) {
  644. // initialize selection based on the current value of the source element
  645. this.initSelection();
  646. // if the user has provided a function that can set selection based on the value of the source element
  647. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  648. this.monitorSource();
  649. }
  650. if (opts.maximumInputLength !== null) {
  651. this.search.attr("maxlength", opts.maximumInputLength);
  652. }
  653. var disabled = opts.element.prop("disabled");
  654. if (disabled === undefined) disabled = false;
  655. this.enable(!disabled);
  656. var readonly = opts.element.prop("readonly");
  657. if (readonly === undefined) readonly = false;
  658. this.readonly(readonly);
  659. // Calculate size of scrollbar
  660. scrollBarDimensions = scrollBarDimensions || measureScrollbar();
  661. this.autofocus = opts.element.prop("autofocus")
  662. opts.element.prop("autofocus", false);
  663. if (this.autofocus) this.focus();
  664. },
  665. // abstract
  666. destroy: function () {
  667. var element=this.opts.element, select2 = element.data("select2");
  668. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  669. if (select2 !== undefined) {
  670. select2.container.remove();
  671. select2.dropdown.remove();
  672. element
  673. .removeClass("select2-offscreen")
  674. .removeData("select2")
  675. .off(".select2")
  676. .prop("autofocus", this.autofocus || false);
  677. if (this.elementTabIndex) {
  678. element.attr({tabindex: this.elementTabIndex});
  679. } else {
  680. element.removeAttr("tabindex");
  681. }
  682. element.show();
  683. }
  684. },
  685. // abstract
  686. optionToData: function(element) {
  687. if (element.is("option")) {
  688. return {
  689. id:element.prop("value"),
  690. text:element.text(),
  691. element: element.get(),
  692. css: element.attr("class"),
  693. disabled: element.prop("disabled"),
  694. locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
  695. };
  696. } else if (element.is("optgroup")) {
  697. return {
  698. text:element.attr("label"),
  699. children:[],
  700. element: element.get(),
  701. css: element.attr("class")
  702. };
  703. }
  704. },
  705. // abstract
  706. prepareOpts: function (opts) {
  707. var element, select, idKey, ajaxUrl, self = this;
  708. element = opts.element;
  709. if (element.get(0).tagName.toLowerCase() === "select") {
  710. this.select = select = opts.element;
  711. }
  712. if (select) {
  713. // these options are not allowed when attached to a select because they are picked up off the element itself
  714. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  715. if (this in opts) {
  716. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  717. }
  718. });
  719. }
  720. opts = $.extend({}, {
  721. populateResults: function(container, results, query) {
  722. var populate, data, result, children, id=this.opts.id;
  723. populate=function(results, container, depth) {
  724. var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
  725. results = opts.sortResults(results, container, query);
  726. for (i = 0, l = results.length; i < l; i = i + 1) {
  727. result=results[i];
  728. disabled = (result.disabled === true);
  729. selectable = (!disabled) && (id(result) !== undefined);
  730. compound=result.children && result.children.length > 0;
  731. node=$("<li></li>");
  732. node.addClass("select2-results-dept-"+depth);
  733. node.addClass("select2-result");
  734. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  735. if (disabled) { node.addClass("select2-disabled"); }
  736. if (compound) { node.addClass("select2-result-with-children"); }
  737. node.addClass(self.opts.formatResultCssClass(result));
  738. label=$(document.createElement("div"));
  739. label.addClass("select2-result-label");
  740. formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
  741. if (formatted!==undefined) {
  742. label.html(formatted);
  743. }
  744. node.append(label);
  745. if (compound) {
  746. innerContainer=$("<ul></ul>");
  747. innerContainer.addClass("select2-result-sub");
  748. populate(result.children, innerContainer, depth+1);
  749. node.append(innerContainer);
  750. }
  751. node.data("select2-data", result);
  752. container.append(node);
  753. }
  754. };
  755. populate(results, container, 0);
  756. }
  757. }, $.fn.select2.defaults, opts);
  758. if (typeof(opts.id) !== "function") {
  759. idKey = opts.id;
  760. opts.id = function (e) { return e[idKey]; };
  761. }
  762. if ($.isArray(opts.element.data("select2Tags"))) {
  763. if ("tags" in opts) {
  764. throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
  765. }
  766. opts.tags=opts.element.data("select2Tags");
  767. }
  768. if (select) {
  769. opts.query = this.bind(function (query) {
  770. var data = { results: [], more: false },
  771. term = query.term,
  772. children, placeholderOption, process;
  773. process=function(element, collection) {
  774. var group;
  775. if (element.is("option")) {
  776. if (query.matcher(term, element.text(), element)) {
  777. collection.push(self.optionToData(element));
  778. }
  779. } else if (element.is("optgroup")) {
  780. group=self.optionToData(element);
  781. element.children().each2(function(i, elm) { process(elm, group.children); });
  782. if (group.children.length>0) {
  783. collection.push(group);
  784. }
  785. }
  786. };
  787. children=element.children();
  788. // ignore the placeholder option if there is one
  789. if (this.getPlaceholder() !== undefined && children.length > 0) {
  790. placeholderOption = this.getPlaceholderOption();
  791. if (placeholderOption) {
  792. children=children.not(placeholderOption);
  793. }
  794. }
  795. children.each2(function(i, elm) { process(elm, data.results); });
  796. query.callback(data);
  797. });
  798. // this is needed because inside val() we construct choices from options and there id is hardcoded
  799. opts.id=function(e) { return e.id; };
  800. opts.formatResultCssClass = function(data) { return data.css; };
  801. } else {
  802. if (!("query" in opts)) {
  803. if ("ajax" in opts) {
  804. ajaxUrl = opts.element.data("ajax-url");
  805. if (ajaxUrl && ajaxUrl.length > 0) {
  806. opts.ajax.url = ajaxUrl;
  807. }
  808. opts.query = ajax.call(opts.element, opts.ajax);
  809. } else if ("data" in opts) {
  810. opts.query = local(opts.data);
  811. } else if ("tags" in opts) {
  812. opts.query = tags(opts.tags);
  813. if (opts.createSearchChoice === undefined) {
  814. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  815. }
  816. if (opts.initSelection === undefined) {
  817. opts.initSelection = function (element, callback) {
  818. var data = [];
  819. $(splitVal(element.val(), opts.separator)).each(function () {
  820. var id = this, text = this, tags=opts.tags;
  821. if ($.isFunction(tags)) tags=tags();
  822. $(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } });
  823. data.push({id: id, text: text});
  824. });
  825. callback(data);
  826. };
  827. }
  828. }
  829. }
  830. }
  831. if (typeof(opts.query) !== "function") {
  832. throw "query function not defined for Select2 " + opts.element.attr("id");
  833. }
  834. return opts;
  835. },
  836. /**
  837. * Monitor the original element for changes and update select2 accordingly
  838. */
  839. // abstract
  840. monitorSource: function () {
  841. var el = this.opts.element, sync;
  842. el.on("change.select2", this.bind(function (e) {
  843. if (this.opts.element.data("select2-change-triggered") !== true) {
  844. this.initSelection();
  845. }
  846. }));
  847. sync = this.bind(function () {
  848. var enabled, readonly, self = this;
  849. // sync enabled state
  850. var disabled = el.prop("disabled");
  851. if (disabled === undefined) disabled = false;
  852. this.enable(!disabled);
  853. var readonly = el.prop("readonly");
  854. if (readonly === undefined) readonly = false;
  855. this.readonly(readonly);
  856. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  857. this.container.addClass(evaluate(this.opts.containerCssClass));
  858. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  859. this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
  860. });
  861. // mozilla and IE
  862. el.on("propertychange.select2 DOMAttrModified.select2", sync);
  863. // hold onto a reference of the callback to work around a chromium bug
  864. if (this.mutationCallback === undefined) {
  865. this.mutationCallback = function (mutations) {
  866. mutations.forEach(sync);
  867. }
  868. }
  869. // safari and chrome
  870. if (typeof WebKitMutationObserver !== "undefined") {
  871. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  872. this.propertyObserver = new WebKitMutationObserver(this.mutationCallback);
  873. this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
  874. }
  875. },
  876. // abstract
  877. triggerSelect: function(data) {
  878. var evt = $.Event("select2-selecting", { val: this.id(data), object: data });
  879. this.opts.element.trigger(evt);
  880. return !evt.isDefaultPrevented();
  881. },
  882. /**
  883. * Triggers the change event on the source element
  884. */
  885. // abstract
  886. triggerChange: function (details) {
  887. details = details || {};
  888. details= $.extend({}, details, { type: "change", val: this.val() });
  889. // prevents recursive triggering
  890. this.opts.element.data("select2-change-triggered", true);
  891. this.opts.element.trigger(details);
  892. this.opts.element.data("select2-change-triggered", false);
  893. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  894. // so here we trigger the click event manually
  895. this.opts.element.click();
  896. // ValidationEngine ignorea the change event and listens instead to blur
  897. // so here we trigger the blur event manually if so desired
  898. if (this.opts.blurOnChange)
  899. this.opts.element.blur();
  900. },
  901. //abstract
  902. isInterfaceEnabled: function()
  903. {
  904. return this.enabledInterface === true;
  905. },
  906. // abstract
  907. enableInterface: function() {
  908. var enabled = this._enabled && !this._readonly,
  909. disabled = !enabled;
  910. if (enabled === this.enabledInterface) return false;
  911. this.container.toggleClass("select2-container-disabled", disabled);
  912. this.close();
  913. this.enabledInterface = enabled;
  914. return true;
  915. },
  916. // abstract
  917. enable: function(enabled) {
  918. if (enabled === undefined) enabled = true;
  919. if (this._enabled === enabled) return false;
  920. this._enabled = enabled;
  921. this.opts.element.prop("disabled", !enabled);
  922. this.enableInterface();
  923. return true;
  924. },
  925. // abstract
  926. readonly: function(enabled) {
  927. if (enabled === undefined) enabled = false;
  928. if (this._readonly === enabled) return false;
  929. this._readonly = enabled;
  930. this.opts.element.prop("readonly", enabled);
  931. this.enableInterface();
  932. return true;
  933. },
  934. // abstract
  935. opened: function () {
  936. return this.container.hasClass("select2-dropdown-open");
  937. },
  938. // abstract
  939. positionDropdown: function() {
  940. var $dropdown = this.dropdown,
  941. offset = this.container.offset(),
  942. height = this.container.outerHeight(false),
  943. width = this.container.outerWidth(false),
  944. dropHeight = $dropdown.outerHeight(false),
  945. viewPortRight = $(window).scrollLeft() + $(window).width(),
  946. viewportBottom = $(window).scrollTop() + $(window).height(),
  947. dropTop = offset.top + height,
  948. dropLeft = offset.left,
  949. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  950. enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
  951. dropWidth = $dropdown.outerWidth(false),
  952. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
  953. aboveNow = $dropdown.hasClass("select2-drop-above"),
  954. bodyOffset,
  955. above,
  956. css,
  957. resultsListNode;
  958. if (this.opts.dropdownAutoWidth) {
  959. resultsListNode = $('.select2-results', $dropdown)[0];
  960. $dropdown.addClass('select2-drop-auto-width');
  961. $dropdown.css('width', '');
  962. // Add scrollbar width to dropdown if vertical scrollbar is present
  963. dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
  964. dropWidth > width ? width = dropWidth : dropWidth = width;
  965. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
  966. }
  967. else {
  968. this.container.removeClass('select2-drop-auto-width');
  969. }
  970. //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  971. //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  972. // fix positioning when body has an offset and is not position: static
  973. if (this.body().css('position') !== 'static') {
  974. bodyOffset = this.body().offset();
  975. dropTop -= bodyOffset.top;
  976. dropLeft -= bodyOffset.left;
  977. }
  978. // always prefer the current above/below alignment, unless there is not enough room
  979. if (aboveNow) {
  980. above = true;
  981. if (!enoughRoomAbove && enoughRoomBelow) above = false;
  982. } else {
  983. above = false;
  984. if (!enoughRoomBelow && enoughRoomAbove) above = true;
  985. }
  986. if (!enoughRoomOnRight) {
  987. dropLeft = offset.left + width - dropWidth;
  988. }
  989. if (above) {
  990. dropTop = offset.top - dropHeight;
  991. this.container.addClass("select2-drop-above");
  992. $dropdown.addClass("select2-drop-above");
  993. }
  994. else {
  995. this.container.removeClass("select2-drop-above");
  996. $dropdown.removeClass("select2-drop-above");
  997. }
  998. css = $.extend({
  999. top: dropTop,
  1000. left: dropLeft,
  1001. width: width
  1002. }, evaluate(this.opts.dropdownCss));
  1003. $dropdown.css(css);
  1004. },
  1005. // abstract
  1006. shouldOpen: function() {
  1007. var event;
  1008. if (this.opened()) return false;
  1009. if (this._enabled === false || this._readonly === true) return false;
  1010. event = $.Event("select2-opening");
  1011. this.opts.element.trigger(event);
  1012. return !event.isDefaultPrevented();
  1013. },
  1014. // abstract
  1015. clearDropdownAlignmentPreference: function() {
  1016. // clear the classes used to figure out the preference of where the dropdown should be opened
  1017. this.container.removeClass("select2-drop-above");
  1018. this.dropdown.removeClass("select2-drop-above");
  1019. },
  1020. /**
  1021. * Opens the dropdown
  1022. *
  1023. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  1024. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  1025. */
  1026. // abstract
  1027. open: function () {
  1028. if (!this.shouldOpen()) return false;
  1029. this.opening();
  1030. return true;
  1031. },
  1032. /**
  1033. * Performs the opening of the dropdown
  1034. */
  1035. // abstract
  1036. opening: function() {
  1037. var cid = this.containerId,
  1038. scroll = "scroll." + cid,
  1039. resize = "resize."+cid,
  1040. orient = "orientationchange."+cid,
  1041. mask, maskCss;
  1042. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  1043. this.clearDropdownAlignmentPreference();
  1044. if(this.dropdown[0] !== this.body().children().last()[0]) {
  1045. this.dropdown.detach().appendTo(this.body());
  1046. }
  1047. // create the dropdown mask if doesnt already exist
  1048. mask = $("#select2-drop-mask");
  1049. if (mask.length == 0) {
  1050. mask = $(document.createElement("div"));
  1051. mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
  1052. mask.hide();
  1053. mask.appendTo(this.body());
  1054. mask.on("mousedown touchstart click", function (e) {
  1055. var dropdown = $("#select2-drop"), self;
  1056. if (dropdown.length > 0) {
  1057. self=dropdown.data("select2");
  1058. if (self.opts.selectOnBlur) {
  1059. self.selectHighlighted({noFocus: true});
  1060. }
  1061. self.close();
  1062. e.preventDefault();
  1063. e.stopPropagation();
  1064. }
  1065. });
  1066. }
  1067. // ensure the mask is always right before the dropdown
  1068. if (this.dropdown.prev()[0] !== mask[0]) {
  1069. this.dropdown.before(mask);
  1070. }
  1071. // move the global id to the correct dropdown
  1072. $("#select2-drop").removeAttr("id");
  1073. this.dropdown.attr("id", "select2-drop");
  1074. // show the elements
  1075. maskCss=_makeMaskCss();
  1076. mask.css(maskCss).show();
  1077. this.dropdown.show();
  1078. this.positionDropdown();
  1079. this.dropdown.addClass("select2-drop-active");
  1080. // attach listeners to events that can change the position of the container and thus require
  1081. // the position of the dropdown to be updated as well so it does not come unglued from the container
  1082. var that = this;
  1083. this.container.parents().add(window).each(function () {
  1084. $(this).on(resize+" "+scroll+" "+orient, function (e) {
  1085. var maskCss=_makeMaskCss();
  1086. $("#select2-drop-mask").css(maskCss);
  1087. that.positionDropdown();
  1088. });
  1089. });
  1090. function _makeMaskCss() {
  1091. return {
  1092. width : Math.max(document.documentElement.scrollWidth, $(window).width()),
  1093. height : Math.max(document.documentElement.scrollHeight, $(window).height())
  1094. }
  1095. }
  1096. },
  1097. // abstract
  1098. close: function () {
  1099. if (!this.opened()) return;
  1100. var cid = this.containerId,
  1101. scroll = "scroll." + cid,
  1102. resize = "resize."+cid,
  1103. orient = "orientationchange."+cid;
  1104. // unbind event listeners
  1105. this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });
  1106. this.clearDropdownAlignmentPreference();
  1107. $("#select2-drop-mask").hide();
  1108. this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
  1109. this.dropdown.hide();
  1110. this.container.removeClass("select2-dropdown-open");
  1111. this.results.empty();
  1112. this.clearSearch();
  1113. this.search.removeClass("select2-active");
  1114. this.opts.element.trigger($.Event("select2-close"));
  1115. },
  1116. /**
  1117. * Opens control, sets input value, and updates results.
  1118. */
  1119. // abstract
  1120. externalSearch: function (term) {
  1121. this.open();
  1122. this.search.val(term);
  1123. this.updateResults(false);
  1124. },
  1125. // abstract
  1126. clearSearch: function () {
  1127. },
  1128. //abstract
  1129. getMaximumSelectionSize: function() {
  1130. return evaluate(this.opts.maximumSelectionSize);
  1131. },
  1132. // abstract
  1133. ensureHighlightVisible: function () {
  1134. var results = this.results, children, index, child, hb, rb, y, more;
  1135. index = this.highlight();
  1136. if (index < 0) return;
  1137. if (index == 0) {
  1138. // if the first element is highlighted scroll all the way to the top,
  1139. // that way any unselectable headers above it will also be scrolled
  1140. // into view
  1141. results.scrollTop(0);
  1142. return;
  1143. }
  1144. children = this.findHighlightableChoices().find('.select2-result-label');
  1145. child = $(children[index]);
  1146. hb = child.offset().top + child.outerHeight(true);
  1147. // if this is the last child lets also make sure select2-more-results is visible
  1148. if (index === children.length - 1) {
  1149. more = results.find("li.select2-more-results");
  1150. if (more.length > 0) {
  1151. hb = more.offset().top + more.outerHeight(true);
  1152. }
  1153. }
  1154. rb = results.offset().top + results.outerHeight(true);
  1155. if (hb > rb) {
  1156. results.scrollTop(results.scrollTop() + (hb - rb));
  1157. }
  1158. y = child.offset().top - results.offset().top;
  1159. // make sure the top of the element is visible
  1160. if (y < 0 && child.css('display') != 'none' ) {
  1161. results.scrollTop(results.scrollTop() + y); // y is negative
  1162. }
  1163. },
  1164. // abstract
  1165. findHighlightableChoices: function() {
  1166. return this.results.find(".select2-result-selectable:not(.select2-selected):not(.select2-disabled)");
  1167. },
  1168. // abstract
  1169. moveHighlight: function (delta) {
  1170. var choices = this.findHighlightableChoices(),
  1171. index = this.highlight();
  1172. while (index > -1 && index < choices.length) {
  1173. index += delta;
  1174. var choice = $(choices[index]);
  1175. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
  1176. this.highlight(index);
  1177. break;
  1178. }
  1179. }
  1180. },
  1181. // abstract
  1182. highlight: function (index) {
  1183. var choices = this.findHighlightableChoices(),
  1184. choice,
  1185. data;
  1186. if (arguments.length === 0) {
  1187. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  1188. }
  1189. if (index >= choices.length) index = choices.length - 1;
  1190. if (index < 0) index = 0;
  1191. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1192. choice = $(choices[index]);
  1193. choice.addClass("select2-highlighted");
  1194. this.ensureHighlightVisible();
  1195. data = choice.data("select2-data");
  1196. if (data) {
  1197. this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
  1198. }
  1199. },
  1200. // abstract
  1201. countSelectableResults: function() {
  1202. return this.findHighlightableChoices().length;
  1203. },
  1204. // abstract
  1205. highlightUnderEvent: function (event) {
  1206. var el = $(event.target).closest(".select2-result-selectable");
  1207. if (el.length > 0 && !el.is(".select2-highlighted")) {
  1208. var choices = this.findHighlightableChoices();
  1209. this.highlight(choices.index(el));
  1210. } else if (el.length == 0) {
  1211. // if we are over an unselectable item remove al highlights
  1212. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1213. }
  1214. },
  1215. // abstract
  1216. loadMoreIfNeeded: function () {
  1217. var results = this.results,
  1218. more = results.find("li.select2-more-results"),
  1219. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  1220. offset = -1, // index of first element without data
  1221. page = this.resultsPage + 1,
  1222. self=this,
  1223. term=this.search.val(),
  1224. context=this.context;
  1225. if (more.length === 0) return;
  1226. below = more.offset().top - results.offset().top - results.height();
  1227. if (below <= this.opts.loadMorePadding) {
  1228. more.addClass("select2-active");
  1229. this.opts.query({
  1230. element: this.opts.element,
  1231. term: term,
  1232. page: page,
  1233. context: context,
  1234. matcher: this.opts.matcher,
  1235. callback: this.bind(function (data) {
  1236. // ignore a response if the select2 has been closed before it was received
  1237. if (!self.opened()) return;
  1238. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  1239. self.postprocessResults(data, false, false);
  1240. if (data.more===true) {
  1241. more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
  1242. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1243. } else {
  1244. more.remove();
  1245. }
  1246. self.positionDropdown();
  1247. self.resultsPage = page;
  1248. self.context = data.context;
  1249. })});
  1250. }
  1251. },
  1252. /**
  1253. * Default tokenizer function which does nothing
  1254. */
  1255. tokenize: function() {
  1256. },
  1257. /**
  1258. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  1259. */
  1260. // abstract
  1261. updateResults: function (initial) {
  1262. var search = this.search,
  1263. results = this.results,
  1264. opts = this.opts,
  1265. data,
  1266. self = this,
  1267. input,
  1268. term = search.val(),
  1269. lastTerm=$.data(this.container, "select2-last-term");
  1270. // prevent duplicate queries against the same term
  1271. if (initial !== true && lastTerm && equal(term, lastTerm)) return;
  1272. $.data(this.container, "select2-last-term", term);
  1273. // if the search is currently hidden we do not alter the results
  1274. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  1275. return;
  1276. }
  1277. function postRender() {
  1278. search.removeClass("select2-active");
  1279. self.positionDropdown();
  1280. }
  1281. function render(html) {
  1282. results.html(html);
  1283. postRender();
  1284. }
  1285. var maxSelSize = this.getMaximumSelectionSize();
  1286. if (maxSelSize >=1) {
  1287. data = this.data();
  1288. if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  1289. render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>");
  1290. return;
  1291. }
  1292. }
  1293. if (search.val().length < opts.minimumInputLength) {
  1294. if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  1295. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  1296. } else {
  1297. render("");
  1298. }
  1299. if (initial && this.showSearch) this.showSearch(true);
  1300. return;
  1301. }
  1302. if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
  1303. if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
  1304. render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>");
  1305. } else {
  1306. render("");
  1307. }
  1308. return;
  1309. }
  1310. if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
  1311. render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
  1312. }
  1313. search.addClass("select2-active");
  1314. // give the tokenizer a chance to pre-process the input
  1315. input = this.tokenize();
  1316. if (input != undefined && input != null) {
  1317. search.val(input);
  1318. }
  1319. this.resultsPage = 1;
  1320. opts.query({
  1321. element: opts.element,
  1322. term: search.val(),
  1323. page: this.resultsPage,
  1324. context: null,
  1325. matcher: opts.matcher,
  1326. callback: this.bind(function (data) {
  1327. var def; // default choice
  1328. // ignore a response if the select2 has been closed before it was received
  1329. if (!this.opened()) {
  1330. this.search.removeClass("select2-active");
  1331. return;
  1332. }
  1333. // save context, if any
  1334. this.context = (data.context===undefined) ? null : data.context;
  1335. // create a default choice and prepend it to the list
  1336. if (this.opts.createSearchChoice && search.val() !== "") {
  1337. def = this.opts.createSearchChoice.call(self, search.val(), data.results);
  1338. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  1339. if ($(data.results).filter(
  1340. function () {
  1341. return equal(self.id(this), self.id(def));
  1342. }).length === 0) {
  1343. data.results.unshift(def);
  1344. }
  1345. }
  1346. }
  1347. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  1348. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  1349. return;
  1350. }
  1351. results.empty();
  1352. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  1353. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  1354. results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
  1355. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1356. }
  1357. this.postprocessResults(data, initial);
  1358. postRender();
  1359. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1360. })});
  1361. },
  1362. // abstract
  1363. cancel: function () {
  1364. this.close();
  1365. },
  1366. // abstract
  1367. blur: function () {
  1368. // if selectOnBlur == true, select the currently highlighted option
  1369. if (this.opts.selectOnBlur)
  1370. this.selectHighlighted({noFocus: true});
  1371. this.close();
  1372. this.container.removeClass("select2-container-active");
  1373. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  1374. if (this.search[0] === document.activeElement) { this.search.blur(); }
  1375. this.clearSearch();
  1376. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1377. },
  1378. // abstract
  1379. focusSearch: function () {
  1380. focus(this.search);
  1381. },
  1382. // abstract
  1383. selectHighlighted: function (options) {
  1384. var index=this.highlight(),
  1385. highlighted=this.results.find(".select2-highlighted"),
  1386. data = highlighted.closest('.select2-result').data("select2-data");
  1387. if (data) {
  1388. this.highlight(index);
  1389. this.onSelect(data, options);
  1390. } else if (options && options.noFocus) {
  1391. this.close();
  1392. }
  1393. },
  1394. // abstract
  1395. getPlaceholder: function () {
  1396. var placeholderOption;
  1397. return this.opts.element.attr("placeholder") ||
  1398. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1399. this.opts.element.data("placeholder") ||
  1400. this.opts.placeholder ||
  1401. ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
  1402. },
  1403. // abstract
  1404. getPlaceholderOption: function() {
  1405. if (this.select) {
  1406. var firstOption = this.select.children().first();
  1407. if (this.opts.placeholderOption !== undefined ) {
  1408. //Determine the placeholder option based on the specified placeholderOption setting
  1409. return (this.opts.placeholderOption === "first" && firstOption) ||
  1410. (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
  1411. } else if (firstOption.text() === "" && firstOption.val() === "") {
  1412. //No explicit placeholder option specified, use the first if it's blank
  1413. return firstOption;
  1414. }
  1415. }
  1416. },
  1417. /**
  1418. * Get the desired width for the container element. This is
  1419. * derived first from option `width` passed to select2, then
  1420. * the inline 'style' on the original element, and finally
  1421. * falls back to the jQuery calculated element width.
  1422. */
  1423. // abstract
  1424. initContainerWidth: function () {
  1425. function resolveContainerWidth() {
  1426. var style, attrs, matches, i, l;
  1427. if (this.opts.width === "off") {
  1428. return null;
  1429. } else if (this.opts.width === "element"){
  1430. return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
  1431. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1432. // check if there is inline style on the element that contains width
  1433. style = this.opts.element.attr('style');
  1434. if (style !== undefined) {
  1435. attrs = style.split(';');
  1436. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1437. matches = attrs[i].replace(/\s/g, '')
  1438. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
  1439. if (matches !== null && matches.length >= 1)
  1440. return matches[1];
  1441. }
  1442. }
  1443. if (this.opts.width === "resolve") {
  1444. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1445. // when attached to input type=hidden or elements hidden via css
  1446. style = this.opts.element.css('width');
  1447. if (style.indexOf("%") > 0) return style;
  1448. // finally, fallback on the calculated width of the element
  1449. return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
  1450. }
  1451. return null;
  1452. } else if ($.isFunction(this.opts.width)) {
  1453. return this.opts.width();
  1454. } else {
  1455. return this.opts.width;
  1456. }
  1457. };
  1458. var width = resolveContainerWidth.call(this);
  1459. if (width !== null) {
  1460. this.container.css("width", width);
  1461. }
  1462. }
  1463. });
  1464. SingleSelect2 = clazz(AbstractSelect2, {
  1465. // single
  1466. createContainer: function () {
  1467. var container = $(document.createElement("div")).attr({
  1468. "class": "select2-container"
  1469. }).html([
  1470. "<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>",
  1471. " <span class='select2-chosen'>&nbsp;</span><abbr class='select2-search-choice-close'></abbr>",
  1472. " <span class='select2-arrow'><b></b></span>",
  1473. "</a>",
  1474. "<input class='select2-focusser select2-offscreen' type='text'/>",
  1475. "<div class='select2-drop select2-display-none'>",
  1476. " <div class='select2-search'>",
  1477. " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'/>",
  1478. " </div>",
  1479. " <ul class='select2-results'>",
  1480. " </ul>",
  1481. "</div>"].join(""));
  1482. return container;
  1483. },
  1484. // single
  1485. enableInterface: function() {
  1486. if (this.parent.enableInterface.apply(this, arguments)) {
  1487. this.focusser.prop("disabled", !this.isInterfaceEnabled());
  1488. }
  1489. },
  1490. // single
  1491. opening: function () {
  1492. var el, range, len;
  1493. if (this.opts.minimumResultsForSearch >= 0) {
  1494. this.showSearch(true);
  1495. }
  1496. this.parent.opening.apply(this, arguments);
  1497. if (this.showSearchInput !== false) {
  1498. // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
  1499. // all other browsers handle this just fine
  1500. this.search.val(this.focusser.val());
  1501. }
  1502. this.search.focus();
  1503. // move the cursor to the end after focussing, otherwise it will be at the beginning and
  1504. // new text will appear *before* focusser.val()
  1505. el = this.search.get(0);
  1506. if (el.createTextRange) {
  1507. range = el.createTextRange();
  1508. range.collapse(false);
  1509. range.select();
  1510. } else if (el.setSelectionRange) {
  1511. len = this.search.val().length;
  1512. el.setSelectionRange(len, len);
  1513. }
  1514. this.focusser.prop("disabled", true).val("");
  1515. this.updateResults(true);
  1516. this.opts.element.trigger($.Event("select2-open"));
  1517. },
  1518. // single
  1519. close: function () {
  1520. if (!this.opened()) return;
  1521. this.parent.close.apply(this, arguments);
  1522. this.focusser.removeAttr("disabled");
  1523. this.focusser.focus();
  1524. },
  1525. // single
  1526. focus: function () {
  1527. if (this.opened()) {
  1528. this.close();
  1529. } else {
  1530. this.focusser.removeAttr("disabled");
  1531. this.focusser.focus();
  1532. }
  1533. },
  1534. // single
  1535. isFocused: function () {
  1536. return this.container.hasClass("select2-container-active");
  1537. },
  1538. // single
  1539. cancel: function () {
  1540. this.parent.cancel.apply(this, arguments);
  1541. this.focusser.removeAttr("disabled");
  1542. this.focusser.focus();
  1543. },
  1544. // single
  1545. initContainer: function () {
  1546. var selection,
  1547. container = this.container,
  1548. dropdown = this.dropdown;
  1549. if (this.opts.minimumResultsForSearch < 0) {
  1550. this.showSearch(false);
  1551. } else {
  1552. this.showSearch(true);
  1553. }
  1554. this.selection = selection = container.find(".select2-choice");
  1555. this.focusser = container.find(".select2-focusser");
  1556. // rewrite labels from original element to focusser
  1557. this.focusser.attr("id", "s2id_autogen"+nextUid());
  1558. $("label[for='" + this.opts.element.attr("id") + "']")
  1559. .attr('for', this.focusser.attr('id'));
  1560. this.focusser.attr("tabindex", this.elementTabIndex);
  1561. this.search.on("keydown", this.bind(function (e) {
  1562. if (!this.isInterfaceEnabled()) return;
  1563. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1564. // prevent the page from scrolling
  1565. killEvent(e);
  1566. return;
  1567. }
  1568. switch (e.which) {
  1569. case KEY.UP:
  1570. case KEY.DOWN:
  1571. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1572. killEvent(e);
  1573. return;
  1574. case KEY.ENTER:
  1575. this.selectHighlighted();
  1576. killEvent(e);
  1577. return;
  1578. case KEY.TAB:
  1579. this.selectHighlighted({noFocus: true});
  1580. return;
  1581. case KEY.ESC:
  1582. this.cancel(e);
  1583. killEvent(e);
  1584. return;
  1585. }
  1586. }));
  1587. this.search.on("blur", this.bind(function(e) {
  1588. // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
  1589. // without this the search field loses focus which is annoying
  1590. if (document.activeElement === this.body().get(0)) {
  1591. window.setTimeout(this.bind(function() {
  1592. this.search.focus();
  1593. }), 0);
  1594. }
  1595. }));
  1596. this.focusser.on("keydown", this.bind(function (e) {
  1597. if (!this.isInterfaceEnabled()) return;
  1598. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1599. return;
  1600. }
  1601. if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
  1602. killEvent(e);
  1603. return;
  1604. }
  1605. if (e.which == KEY.DOWN || e.which == KEY.UP
  1606. || (e.which == KEY.ENTER && this.opts.openOnEnter)) {
  1607. if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;
  1608. this.open();
  1609. killEvent(e);
  1610. return;
  1611. }
  1612. if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
  1613. if (this.opts.allowClear) {
  1614. this.clear();
  1615. }
  1616. killEvent(e);
  1617. return;
  1618. }
  1619. }));
  1620. installKeyUpChangeEvent(this.focusser);
  1621. this.focusser.on("keyup-change input", this.bind(function(e) {
  1622. if (this.opts.minimumResultsForSearch >= 0) {
  1623. e.stopPropagation();
  1624. if (this.opened()) return;
  1625. this.open();
  1626. }
  1627. }));
  1628. selection.on("mousedown", "abbr", this.bind(function (e) {
  1629. if (!this.isInterfaceEnabled()) return;
  1630. this.clear();
  1631. killEventImmediately(e);
  1632. this.close();
  1633. this.selection.focus();
  1634. }));
  1635. selection.on("mousedown", this.bind(function (e) {
  1636. if (!this.container.hasClass("select2-container-active")) {
  1637. this.opts.element.trigger($.Event("select2-focus"));
  1638. }
  1639. if (this.opened()) {
  1640. this.close();
  1641. } else if (this.isInterfaceEnabled()) {
  1642. this.open();
  1643. }
  1644. killEvent(e);
  1645. }));
  1646. dropdown.on("mousedown", this.bind(function() { this.search.focus(); }));
  1647. selection.on("focus", this.bind(function(e) {
  1648. killEvent(e);
  1649. }));
  1650. this.focusser.on("focus", this.bind(function(){
  1651. if (!this.container.hasClass("select2-container-active")) {
  1652. this.opts.element.trigger($.Event("select2-focus"));
  1653. }
  1654. this.container.addClass("select2-container-active");
  1655. })).on("blur", this.bind(function() {
  1656. if (!this.opened()) {
  1657. this.container.removeClass("select2-container-active");
  1658. this.opts.element.trigger($.Event("select2-blur"));
  1659. }
  1660. }));
  1661. this.search.on("focus", this.bind(function(){
  1662. if (!this.container.hasClass("select2-container-active")) {
  1663. this.opts.element.trigger($.Event("select2-focus"));
  1664. }
  1665. this.container.addClass("select2-container-active");
  1666. }));
  1667. this.initContainerWidth();
  1668. this.opts.element.addClass("select2-offscreen");
  1669. this.setPlaceholder();
  1670. },
  1671. // single
  1672. clear: function(triggerChange) {
  1673. var data=this.selection.data("select2-data");
  1674. if (data) { // guard against queued quick consecutive clicks
  1675. var placeholderOption = this.getPlaceholderOption();
  1676. this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
  1677. this.selection.find(".select2-chosen").empty();
  1678. this.selection.removeData("select2-data");
  1679. this.setPlaceholder();
  1680. if (triggerChange !== false){
  1681. this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
  1682. this.triggerChange({removed:data});
  1683. }
  1684. }
  1685. },
  1686. /**
  1687. * Sets selection based on source element's value
  1688. */
  1689. // single
  1690. initSelection: function () {
  1691. var selected;
  1692. if (this.isPlaceholderOptionSelected()) {
  1693. this.updateSelection([]);
  1694. this.close();
  1695. this.setPlaceholder();
  1696. } else {
  1697. var self = this;
  1698. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1699. if (selected !== undefined && selected !== null) {
  1700. self.updateSelection(selected);
  1701. self.close();
  1702. self.setPlaceholder();
  1703. }
  1704. });
  1705. }
  1706. },
  1707. isPlaceholderOptionSelected: function() {
  1708. var placeholderOption;
  1709. return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.is(':selected')) ||
  1710. (this.opts.element.val() === "") ||
  1711. (this.opts.element.val() === undefined) ||
  1712. (this.opts.element.val() === null);
  1713. },
  1714. // single
  1715. prepareOpts: function () {
  1716. var opts = this.parent.prepareOpts.apply(this, arguments),
  1717. self=this;
  1718. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1719. // install the selection initializer
  1720. opts.initSelection = function (element, callback) {
  1721. var selected = element.find(":selected");
  1722. // a single select box always has a value, no need to null check 'selected'
  1723. callback(self.optionToData(selected));
  1724. };
  1725. } else if ("data" in opts) {
  1726. // install default initSelection when applied to hidden input and data is local
  1727. opts.initSelection = opts.initSelection || function (element, callback) {
  1728. var id = element.val();
  1729. //search in data by id, storing the actual matching item
  1730. var match = null;
  1731. opts.query({
  1732. matcher: function(term, text, el){
  1733. var is_match = equal(id, opts.id(el));
  1734. if (is_match) {
  1735. match = el;
  1736. }
  1737. return is_match;
  1738. },
  1739. callback: !$.isFunction(callback) ? $.noop : function() {
  1740. callback(match);
  1741. }
  1742. });
  1743. };
  1744. }
  1745. return opts;
  1746. },
  1747. // single
  1748. getPlaceholder: function() {
  1749. // if a placeholder is specified on a single select without a valid placeholder option ignore it
  1750. if (this.select) {
  1751. if (this.getPlaceholderOption() === undefined) {
  1752. return undefined;
  1753. }
  1754. }
  1755. return this.parent.getPlaceholder.apply(this, arguments);
  1756. },
  1757. // single
  1758. setPlaceholder: function () {
  1759. var placeholder = this.getPlaceholder();
  1760. if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {
  1761. // check for a placeholder option if attached to a select
  1762. if (this.select && this.getPlaceholderOption() === undefined) return;
  1763. this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));
  1764. this.selection.addClass("select2-default");
  1765. this.container.removeClass("select2-allowclear");
  1766. }
  1767. },
  1768. // single
  1769. postprocessResults: function (data, initial, noHighlightUpdate) {
  1770. var selected = 0, self = this, showSearchInput = true;
  1771. // find the selected element in the result list
  1772. this.findHighlightableChoices().each2(function (i, elm) {
  1773. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1774. selected = i;
  1775. return false;
  1776. }
  1777. });
  1778. // and highlight it
  1779. if (noHighlightUpdate !== false) {
  1780. if (initial === true && selected >= 0) {
  1781. this.highlight(selected);
  1782. } else {
  1783. this.highlight(0);
  1784. }
  1785. }
  1786. // hide the search box if this is the first we got the results and there are enough of them for search
  1787. if (initial === true) {
  1788. var min = this.opts.minimumResultsForSearch;
  1789. if (min >= 0) {
  1790. this.showSearch(countResults(data.results) >= min);
  1791. }
  1792. }
  1793. },
  1794. // single
  1795. showSearch: function(showSearchInput) {
  1796. if (this.showSearchInput === showSearchInput) return;
  1797. this.showSearchInput = showSearchInput;
  1798. this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
  1799. this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
  1800. //add "select2-with-searchbox" to the container if search box is shown
  1801. $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
  1802. },
  1803. // single
  1804. onSelect: function (data, options) {
  1805. if (!this.triggerSelect(data)) { return; }
  1806. var old = this.opts.element.val(),
  1807. oldData = this.data();
  1808. this.opts.element.val(this.id(data));
  1809. this.updateSelection(data);
  1810. this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
  1811. this.close();
  1812. if (!options || !options.noFocus)
  1813. this.selection.focus();
  1814. if (!equal(old, this.id(data))) { this.triggerChange({added:data,removed:oldData}); }
  1815. },
  1816. // single
  1817. updateSelection: function (data) {
  1818. var container=this.selection.find(".select2-chosen"), formatted, cssClass;
  1819. this.selection.data("select2-data", data);
  1820. container.empty();
  1821. formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
  1822. if (formatted !== undefined) {
  1823. container.append(formatted);
  1824. }
  1825. cssClass=this.opts.formatSelectionCssClass(data, container);
  1826. if (cssClass !== undefined) {
  1827. container.addClass(cssClass);
  1828. }
  1829. this.selection.removeClass("select2-default");
  1830. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1831. this.container.addClass("select2-allowclear");
  1832. }
  1833. },
  1834. // single
  1835. val: function () {
  1836. var val,
  1837. triggerChange = false,
  1838. data = null,
  1839. self = this,
  1840. oldData = this.data();
  1841. if (arguments.length === 0) {
  1842. return this.opts.element.val();
  1843. }
  1844. val = arguments[0];
  1845. if (arguments.length > 1) {
  1846. triggerChange = arguments[1];
  1847. }
  1848. if (this.select) {
  1849. this.select
  1850. .val(val)
  1851. .find(":selected").each2(function (i, elm) {
  1852. data = self.optionToData(elm);
  1853. return false;
  1854. });
  1855. this.updateSelection(data);
  1856. this.setPlaceholder();
  1857. if (triggerChange) {
  1858. this.triggerChange({added: data, removed:oldData});
  1859. }
  1860. } else {
  1861. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  1862. if (!val && val !== 0) {
  1863. this.clear(triggerChange);
  1864. return;
  1865. }
  1866. if (this.opts.initSelection === undefined) {
  1867. throw new Error("cannot call val() if initSelection() is not defined");
  1868. }
  1869. this.opts.element.val(val);
  1870. this.opts.initSelection(this.opts.element, function(data){
  1871. self.opts.element.val(!data ? "" : self.id(data));
  1872. self.updateSelection(data);
  1873. self.setPlaceholder();
  1874. if (triggerChange) {
  1875. self.triggerChange({added: data, removed:oldData});
  1876. }
  1877. });
  1878. }
  1879. },
  1880. // single
  1881. clearSearch: function () {
  1882. this.search.val("");
  1883. this.focusser.val("");
  1884. },
  1885. // single
  1886. data: function(value, triggerChange) {
  1887. var data;
  1888. if (arguments.length === 0) {
  1889. data = this.selection.data("select2-data");
  1890. if (data == undefined) data = null;
  1891. return data;
  1892. } else {
  1893. if (!value || value === "") {
  1894. this.clear(triggerChange);
  1895. } else {
  1896. data = this.data();
  1897. this.opts.element.val(!value ? "" : this.id(value));
  1898. this.updateSelection(value);
  1899. if (triggerChange) {
  1900. this.triggerChange({added: value, removed:data});
  1901. }
  1902. }
  1903. }
  1904. }
  1905. });
  1906. MultiSelect2 = clazz(AbstractSelect2, {
  1907. // multi
  1908. createContainer: function () {
  1909. var container = $(document.createElement("div")).attr({
  1910. "class": "select2-container select2-container-multi"
  1911. }).html([
  1912. "<ul class='select2-choices'>",
  1913. " <li class='select2-search-field'>",
  1914. " <input type='text' autocomplete='off' autocorrect='off' autocapitilize='off' spellcheck='false' class='select2-input'>",
  1915. " </li>",
  1916. "</ul>",
  1917. "<div class='select2-drop select2-drop-multi select2-display-none'>",
  1918. " <ul class='select2-results'>",
  1919. " </ul>",
  1920. "</div>"].join(""));
  1921. return container;
  1922. },
  1923. // multi
  1924. prepareOpts: function () {
  1925. var opts = this.parent.prepareOpts.apply(this, arguments),
  1926. self=this;
  1927. // TODO validate placeholder is a string if specified
  1928. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1929. // install sthe selection initializer
  1930. opts.initSelection = function (element, callback) {
  1931. var data = [];
  1932. element.find(":selected").each2(function (i, elm) {
  1933. data.push(self.optionToData(elm));
  1934. });
  1935. callback(data);
  1936. };
  1937. } else if ("data" in opts) {
  1938. // install default initSelection when applied to hidden input and data is local
  1939. opts.initSelection = opts.initSelection || function (element, callback) {
  1940. var ids = splitVal(element.val(), opts.separator);
  1941. //search in data by array of ids, storing matching items in a list
  1942. var matches = [];
  1943. opts.query({
  1944. matcher: function(term, text, el){
  1945. var is_match = $.grep(ids, function(id) {
  1946. return equal(id, opts.id(el));
  1947. }).length;
  1948. if (is_match) {
  1949. matches.push(el);
  1950. }
  1951. return is_match;
  1952. },
  1953. callback: !$.isFunction(callback) ? $.noop : function() {
  1954. // reorder matches based on the order they appear in the ids array because right now
  1955. // they are in the order in which they appear in data array
  1956. var ordered = [];
  1957. for (var i = 0; i < ids.length; i++) {
  1958. var id = ids[i];
  1959. for (var j = 0; j < matches.length; j++) {
  1960. var match = matches[j];
  1961. if (equal(id, opts.id(match))) {
  1962. ordered.push(match);
  1963. matches.splice(j, 1);
  1964. break;
  1965. }
  1966. }
  1967. }
  1968. callback(ordered);
  1969. }
  1970. });
  1971. };
  1972. }
  1973. return opts;
  1974. },
  1975. selectChoice: function (choice) {
  1976. var selected = this.container.find(".select2-search-choice-focus");
  1977. if (selected.length && choice && choice[0] == selected[0]) {
  1978. } else {
  1979. if (selected.length) {
  1980. this.opts.element.trigger("choice-deselected", selected);
  1981. }
  1982. selected.removeClass("select2-search-choice-focus");
  1983. if (choice && choice.length) {
  1984. this.close();
  1985. choice.addClass("select2-search-choice-focus");
  1986. this.opts.element.trigger("choice-selected", choice);
  1987. }
  1988. }
  1989. },
  1990. // multi
  1991. initContainer: function () {
  1992. var selector = ".select2-choices", selection;
  1993. this.searchContainer = this.container.find(".select2-search-field");
  1994. this.selection = selection = this.container.find(selector);
  1995. var _this = this;
  1996. this.selection.on("mousedown", ".select2-search-choice", function (e) {
  1997. //killEvent(e);
  1998. _this.search[0].focus();
  1999. _this.selectChoice($(this));
  2000. })
  2001. // rewrite labels from original element to focusser
  2002. this.search.attr("id", "s2id_autogen"+nextUid());
  2003. $("label[for='" + this.opts.element.attr("id") + "']")
  2004. .attr('for', this.search.attr('id'));
  2005. this.search.on("input paste", this.bind(function() {
  2006. if (!this.isInterfaceEnabled()) return;
  2007. if (!this.opened()) {
  2008. this.open();
  2009. }
  2010. }));
  2011. this.search.attr("tabindex", this.elementTabIndex);
  2012. this.keydowns = 0;
  2013. this.search.on("keydown", this.bind(function (e) {
  2014. if (!this.isInterfaceEnabled()) return;
  2015. ++this.keydowns;
  2016. var selected = selection.find(".select2-search-choice-focus");
  2017. var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
  2018. var next = selected.next(".select2-search-choice:not(.select2-locked)");
  2019. var pos = getCursorInfo(this.search);
  2020. if (selected.length &&
  2021. (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
  2022. var selectedChoice = selected;
  2023. if (e.which == KEY.LEFT && prev.length) {
  2024. selectedChoice = prev;
  2025. }
  2026. else if (e.which == KEY.RIGHT) {
  2027. selectedChoice = next.length ? next : null;
  2028. }
  2029. else if (e.which === KEY.BACKSPACE) {
  2030. this.unselect(selected.first());
  2031. this.search.width(10);
  2032. selectedChoice = prev.length ? prev : next;
  2033. } else if (e.which == KEY.DELETE) {
  2034. this.unselect(selected.first());
  2035. this.search.width(10);
  2036. selectedChoice = next.length ? next : null;
  2037. } else if (e.which == KEY.ENTER) {
  2038. selectedChoice = null;
  2039. }
  2040. this.selectChoice(selectedChoice);
  2041. killEvent(e);
  2042. if (!selectedChoice || !selectedChoice.length) {
  2043. this.open();
  2044. }
  2045. return;
  2046. } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
  2047. || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {
  2048. this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
  2049. killEvent(e);
  2050. return;
  2051. } else {
  2052. this.selectChoice(null);
  2053. }
  2054. if (this.opened()) {
  2055. switch (e.which) {
  2056. case KEY.UP:
  2057. case KEY.DOWN:
  2058. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  2059. killEvent(e);
  2060. return;
  2061. case KEY.ENTER:
  2062. this.selectHighlighted();
  2063. killEvent(e);
  2064. return;
  2065. case KEY.TAB:
  2066. this.selectHighlighted({noFocus:true});
  2067. this.close();
  2068. return;
  2069. case KEY.ESC:
  2070. this.cancel(e);
  2071. killEvent(e);
  2072. return;
  2073. }
  2074. }
  2075. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  2076. || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  2077. return;
  2078. }
  2079. if (e.which === KEY.ENTER) {
  2080. if (this.opts.openOnEnter === false) {
  2081. return;
  2082. } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
  2083. return;
  2084. }
  2085. }
  2086. this.open();
  2087. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  2088. // prevent the page from scrolling
  2089. killEvent(e);
  2090. }
  2091. if (e.which === KEY.ENTER) {
  2092. // prevent form from being submitted
  2093. killEvent(e);
  2094. }
  2095. }));
  2096. this.search.on("keyup", this.bind(function (e) {
  2097. this.keydowns = 0;
  2098. this.resizeSearch();
  2099. })
  2100. );
  2101. this.search.on("blur", this.bind(function(e) {
  2102. this.container.removeClass("select2-container-active");
  2103. this.search.removeClass("select2-focused");
  2104. this.selectChoice(null);
  2105. if (!this.opened()) this.clearSearch();
  2106. e.stopImmediatePropagation();
  2107. this.opts.element.trigger($.Event("select2-blur"));
  2108. }));
  2109. this.container.on("click", selector, this.bind(function (e) {
  2110. if (!this.isInterfaceEnabled()) return;
  2111. if ($(e.target).closest(".select2-search-choice").length > 0) {
  2112. // clicked inside a select2 search choice, do not open
  2113. return;
  2114. }
  2115. this.selectChoice(null);
  2116. this.clearPlaceholder();
  2117. if (!this.container.hasClass("select2-container-active")) {
  2118. this.opts.element.trigger($.Event("select2-focus"));
  2119. }
  2120. this.open();
  2121. this.focusSearch();
  2122. e.preventDefault();
  2123. }));
  2124. this.container.on("focus", selector, this.bind(function () {
  2125. if (!this.isInterfaceEnabled()) return;
  2126. if (!this.container.hasClass("select2-container-active")) {
  2127. this.opts.element.trigger($.Event("select2-focus"));
  2128. }
  2129. this.container.addClass("select2-container-active");
  2130. this.dropdown.addClass("select2-drop-active");
  2131. this.clearPlaceholder();
  2132. }));
  2133. this.initContainerWidth();
  2134. this.opts.element.addClass("select2-offscreen");
  2135. // set the placeholder if necessary
  2136. this.clearSearch();
  2137. },
  2138. // multi
  2139. enableInterface: function() {
  2140. if (this.parent.enableInterface.apply(this, arguments)) {
  2141. this.search.prop("disabled", !this.isInterfaceEnabled());
  2142. }
  2143. },
  2144. // multi
  2145. initSelection: function () {
  2146. var data;
  2147. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  2148. this.updateSelection([]);
  2149. this.close();
  2150. // set the placeholder if necessary
  2151. this.clearSearch();
  2152. }
  2153. if (this.select || this.opts.element.val() !== "") {
  2154. var self = this;
  2155. this.opts.initSelection.call(null, this.opts.element, function(data){
  2156. if (data !== undefined && data !== null) {
  2157. self.updateSelection(data);
  2158. self.close();
  2159. // set the placeholder if necessary
  2160. self.clearSearch();
  2161. }
  2162. });
  2163. }
  2164. },
  2165. // multi
  2166. clearSearch: function () {
  2167. var placeholder = this.getPlaceholder(),
  2168. maxWidth = this.getMaxSearchWidth();
  2169. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  2170. this.search.val(placeholder).addClass("select2-default");
  2171. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  2172. // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944
  2173. this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
  2174. } else {
  2175. this.search.val("").width(10);
  2176. }
  2177. },
  2178. // multi
  2179. clearPlaceholder: function () {
  2180. if (this.search.hasClass("select2-default")) {
  2181. this.search.val("").removeClass("select2-default");
  2182. }
  2183. },
  2184. // multi
  2185. opening: function () {
  2186. this.clearPlaceholder(); // should be done before super so placeholder is not used to search
  2187. this.resizeSearch();
  2188. this.parent.opening.apply(this, arguments);
  2189. this.focusSearch();
  2190. this.updateResults(true);
  2191. this.search.focus();
  2192. this.opts.element.trigger($.Event("select2-open"));
  2193. },
  2194. // multi
  2195. close: function () {
  2196. if (!this.opened()) return;
  2197. this.parent.close.apply(this, arguments);
  2198. },
  2199. // multi
  2200. focus: function () {
  2201. this.close();
  2202. this.search.focus();
  2203. },
  2204. // multi
  2205. isFocused: function () {
  2206. return this.search.hasClass("select2-focused");
  2207. },
  2208. // multi
  2209. updateSelection: function (data) {
  2210. var ids = [], filtered = [], self = this;
  2211. // filter out duplicates
  2212. $(data).each(function () {
  2213. if (indexOf(self.id(this), ids) < 0) {
  2214. ids.push(self.id(this));
  2215. filtered.push(this);
  2216. }
  2217. });
  2218. data = filtered;
  2219. this.selection.find(".select2-search-choice").remove();
  2220. $(data).each(function () {
  2221. self.addSelectedChoice(this);
  2222. });
  2223. self.postprocessResults();
  2224. },
  2225. // multi
  2226. tokenize: function() {
  2227. var input = this.search.val();
  2228. input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
  2229. if (input != null && input != undefined) {
  2230. this.search.val(input);
  2231. if (input.length > 0) {
  2232. this.open();
  2233. }
  2234. }
  2235. },
  2236. // multi
  2237. onSelect: function (data, options) {
  2238. if (!this.triggerSelect(data)) { return; }
  2239. this.addSelectedChoice(data);
  2240. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  2241. if (this.select || !this.opts.closeOnSelect) this.postprocessResults();
  2242. if (this.opts.closeOnSelect) {
  2243. this.close();
  2244. this.search.width(10);
  2245. } else {
  2246. if (this.countSelectableResults()>0) {
  2247. this.search.width(10);
  2248. this.resizeSearch();
  2249. if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
  2250. // if we reached max selection size repaint the results so choices
  2251. // are replaced with the max selection reached message
  2252. this.updateResults(true);
  2253. }
  2254. this.positionDropdown();
  2255. } else {
  2256. // if nothing left to select close
  2257. this.close();
  2258. this.search.width(10);
  2259. }
  2260. }
  2261. // since its not possible to select an element that has already been
  2262. // added we do not need to check if this is a new element before firing change
  2263. this.triggerChange({ added: data });
  2264. if (!options || !options.noFocus)
  2265. this.focusSearch();
  2266. },
  2267. // multi
  2268. cancel: function () {
  2269. this.close();
  2270. this.focusSearch();
  2271. },
  2272. addSelectedChoice: function (data) {
  2273. var enableChoice = !data.locked,
  2274. enabledItem = $(
  2275. "<li class='select2-search-choice'>" +
  2276. " <div></div>" +
  2277. " <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
  2278. "</li>"),
  2279. disabledItem = $(
  2280. "<li class='select2-search-choice select2-locked'>" +
  2281. "<div></div>" +
  2282. "</li>");
  2283. var choice = enableChoice ? enabledItem : disabledItem,
  2284. id = this.id(data),
  2285. val = this.getVal(),
  2286. formatted,
  2287. cssClass;
  2288. formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
  2289. if (formatted != undefined) {
  2290. choice.find("div").replaceWith("<div>"+formatted+"</div>");
  2291. }
  2292. cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
  2293. if (cssClass != undefined) {
  2294. choice.addClass(cssClass);
  2295. }
  2296. if(enableChoice){
  2297. choice.find(".select2-search-choice-close")
  2298. .on("mousedown", killEvent)
  2299. .on("click dblclick", this.bind(function (e) {
  2300. if (!this.isInterfaceEnabled()) return;
  2301. $(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
  2302. this.unselect($(e.target));
  2303. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  2304. this.close();
  2305. this.focusSearch();
  2306. })).dequeue();
  2307. killEvent(e);
  2308. })).on("focus", this.bind(function () {
  2309. if (!this.isInterfaceEnabled()) return;
  2310. this.container.addClass("select2-container-active");
  2311. this.dropdown.addClass("select2-drop-active");
  2312. }));
  2313. }
  2314. choice.data("select2-data", data);
  2315. choice.insertBefore(this.searchContainer);
  2316. val.push(id);
  2317. this.setVal(val);
  2318. },
  2319. // multi
  2320. unselect: function (selected) {
  2321. var val = this.getVal(),
  2322. data,
  2323. index;
  2324. selected = selected.closest(".select2-search-choice");
  2325. if (selected.length === 0) {
  2326. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  2327. }
  2328. data = selected.data("select2-data");
  2329. if (!data) {
  2330. // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
  2331. // and invoked on an element already removed
  2332. return;
  2333. }
  2334. index = indexOf(this.id(data), val);
  2335. if (index >= 0) {
  2336. val.splice(index, 1);
  2337. this.setVal(val);
  2338. if (this.select) this.postprocessResults();
  2339. }
  2340. selected.remove();
  2341. this.opts.element.trigger({ type: "removed", val: this.id(data), choice: data });
  2342. this.triggerChange({ removed: data });
  2343. },
  2344. // multi
  2345. postprocessResults: function (data, initial, noHighlightUpdate) {
  2346. var val = this.getVal(),
  2347. choices = this.results.find(".select2-result"),
  2348. compound = this.results.find(".select2-result-with-children"),
  2349. self = this;
  2350. choices.each2(function (i, choice) {
  2351. var id = self.id(choice.data("select2-data"));
  2352. if (indexOf(id, val) >= 0) {
  2353. choice.addClass("select2-selected");
  2354. // mark all children of the selected parent as selected
  2355. choice.find(".select2-result-selectable").addClass("select2-selected");
  2356. }
  2357. });
  2358. compound.each2(function(i, choice) {
  2359. // hide an optgroup if it doesnt have any selectable children
  2360. if (!choice.is('.select2-result-selectable')
  2361. && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
  2362. choice.addClass("select2-selected");
  2363. }
  2364. });
  2365. if (this.highlight() == -1 && noHighlightUpdate !== false){
  2366. self.highlight(0);
  2367. }
  2368. //If all results are chosen render formatNoMAtches
  2369. if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
  2370. if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
  2371. if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
  2372. this.results.append("<li class='select2-no-results'>" + self.opts.formatNoMatches(self.search.val()) + "</li>");
  2373. }
  2374. }
  2375. }
  2376. },
  2377. // multi
  2378. getMaxSearchWidth: function() {
  2379. return this.selection.width() - getSideBorderPadding(this.search);
  2380. },
  2381. // multi
  2382. resizeSearch: function () {
  2383. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  2384. sideBorderPadding = getSideBorderPadding(this.search);
  2385. minimumWidth = measureTextWidth(this.search) + 10;
  2386. left = this.search.offset().left;
  2387. maxWidth = this.selection.width();
  2388. containerLeft = this.selection.offset().left;
  2389. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  2390. if (searchWidth < minimumWidth) {
  2391. searchWidth = maxWidth - sideBorderPadding;
  2392. }
  2393. if (searchWidth < 40) {
  2394. searchWidth = maxWidth - sideBorderPadding;
  2395. }
  2396. if (searchWidth <= 0) {
  2397. searchWidth = minimumWidth;
  2398. }
  2399. this.search.width(searchWidth);
  2400. },
  2401. // multi
  2402. getVal: function () {
  2403. var val;
  2404. if (this.select) {
  2405. val = this.select.val();
  2406. return val === null ? [] : val;
  2407. } else {
  2408. val = this.opts.element.val();
  2409. return splitVal(val, this.opts.separator);
  2410. }
  2411. },
  2412. // multi
  2413. setVal: function (val) {
  2414. var unique;
  2415. if (this.select) {
  2416. this.select.val(val);
  2417. } else {
  2418. unique = [];
  2419. // filter out duplicates
  2420. $(val).each(function () {
  2421. if (indexOf(this, unique) < 0) unique.push(this);
  2422. });
  2423. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  2424. }
  2425. },
  2426. // multi
  2427. buildChangeDetails: function (old, current) {
  2428. var current = current.slice(0),
  2429. old = old.slice(0);
  2430. // remove intersection from each array
  2431. for (var i = 0; i < current.length; i++) {
  2432. for (var j = 0; j < old.length; j++) {
  2433. if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
  2434. current.splice(i, 1);
  2435. i--;
  2436. old.splice(j, 1);
  2437. j--;
  2438. }
  2439. }
  2440. }
  2441. return {added: current, removed: old};
  2442. },
  2443. // multi
  2444. val: function (val, triggerChange) {
  2445. var oldData, self=this, changeDetails;
  2446. if (arguments.length === 0) {
  2447. return this.getVal();
  2448. }
  2449. oldData=this.data();
  2450. if (!oldData.length) oldData=[];
  2451. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2452. if (!val && val !== 0) {
  2453. this.opts.element.val("");
  2454. this.updateSelection([]);
  2455. this.clearSearch();
  2456. if (triggerChange) {
  2457. this.triggerChange({added: this.data(), removed: oldData});
  2458. }
  2459. return;
  2460. }
  2461. // val is a list of ids
  2462. this.setVal(val);
  2463. if (this.select) {
  2464. this.opts.initSelection(this.select, this.bind(this.updateSelection));
  2465. if (triggerChange) {
  2466. this.triggerChange(this.buildChangeDetails(oldData, this.data()));
  2467. }
  2468. } else {
  2469. if (this.opts.initSelection === undefined) {
  2470. throw new Error("val() cannot be called if initSelection() is not defined");
  2471. }
  2472. this.opts.initSelection(this.opts.element, function(data){
  2473. var ids=$.map(data, self.id);
  2474. self.setVal(ids);
  2475. self.updateSelection(data);
  2476. self.clearSearch();
  2477. if (triggerChange) {
  2478. self.triggerChange(this.buildChangeDetails(oldData, this.data()));
  2479. }
  2480. });
  2481. }
  2482. this.clearSearch();
  2483. },
  2484. // multi
  2485. onSortStart: function() {
  2486. if (this.select) {
  2487. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  2488. }
  2489. // collapse search field into 0 width so its container can be collapsed as well
  2490. this.search.width(0);
  2491. // hide the container
  2492. this.searchContainer.hide();
  2493. },
  2494. // multi
  2495. onSortEnd:function() {
  2496. var val=[], self=this;
  2497. // show search and move it to the end of the list
  2498. this.searchContainer.show();
  2499. // make sure the search container is the last item in the list
  2500. this.searchContainer.appendTo(this.searchContainer.parent());
  2501. // since we collapsed the width in dragStarted, we resize it here
  2502. this.resizeSearch();
  2503. // update selection
  2504. this.selection.find(".select2-search-choice").each(function() {
  2505. val.push(self.opts.id($(this).data("select2-data")));
  2506. });
  2507. this.setVal(val);
  2508. this.triggerChange();
  2509. },
  2510. // multi
  2511. data: function(values, triggerChange) {
  2512. var self=this, ids, old;
  2513. if (arguments.length === 0) {
  2514. return this.selection
  2515. .find(".select2-search-choice")
  2516. .map(function() { return $(this).data("select2-data"); })
  2517. .get();
  2518. } else {
  2519. old = this.data();
  2520. if (!values) { values = []; }
  2521. ids = $.map(values, function(e) { return self.opts.id(e); });
  2522. this.setVal(ids);
  2523. this.updateSelection(values);
  2524. this.clearSearch();
  2525. if (triggerChange) {
  2526. this.triggerChange(this.buildChangeDetails(old, this.data()));
  2527. }
  2528. }
  2529. }
  2530. });
  2531. $.fn.select2 = function () {
  2532. var args = Array.prototype.slice.call(arguments, 0),
  2533. opts,
  2534. select2,
  2535. method, value, multiple,
  2536. allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "readonly", "positionDropdown", "data", "search"],
  2537. valueMethods = ["val", "opened", "isFocused", "container", "data"],
  2538. methodsMap = { search: "externalSearch" };
  2539. this.each(function () {
  2540. if (args.length === 0 || typeof(args[0]) === "object") {
  2541. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  2542. opts.element = $(this);
  2543. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2544. multiple = opts.element.prop("multiple");
  2545. } else {
  2546. multiple = opts.multiple || false;
  2547. if ("tags" in opts) {opts.multiple = multiple = true;}
  2548. }
  2549. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  2550. select2.init(opts);
  2551. } else if (typeof(args[0]) === "string") {
  2552. if (indexOf(args[0], allowedMethods) < 0) {
  2553. throw "Unknown method: " + args[0];
  2554. }
  2555. value = undefined;
  2556. select2 = $(this).data("select2");
  2557. if (select2 === undefined) return;
  2558. method=args[0];
  2559. if (method === "container") {
  2560. value = select2.container;
  2561. } else if (method === "dropdown") {
  2562. value = select2.dropdown;
  2563. } else {
  2564. if (methodsMap[method]) method = methodsMap[method];
  2565. value = select2[method].apply(select2, args.slice(1));
  2566. }
  2567. if (indexOf(args[0], valueMethods) >= 0) {
  2568. return false;
  2569. }
  2570. } else {
  2571. throw "Invalid arguments to select2 plugin: " + args;
  2572. }
  2573. });
  2574. return (value === undefined) ? this : value;
  2575. };
  2576. // plugin defaults, accessible to users
  2577. $.fn.select2.defaults = {
  2578. width: "copy",
  2579. loadMorePadding: 0,
  2580. closeOnSelect: true,
  2581. openOnEnter: true,
  2582. containerCss: {},
  2583. dropdownCss: {},
  2584. containerCssClass: "",
  2585. dropdownCssClass: "",
  2586. formatResult: function(result, container, query, escapeMarkup) {
  2587. var markup=[];
  2588. markMatch(result.text, query.term, markup, escapeMarkup);
  2589. return markup.join("");
  2590. },
  2591. formatSelection: function (data, container, escapeMarkup) {
  2592. return data ? escapeMarkup(data.text) : undefined;
  2593. },
  2594. sortResults: function (results, container, query) {
  2595. return results;
  2596. },
  2597. formatResultCssClass: function(data) {return undefined;},
  2598. formatSelectionCssClass: function(data, container) {return undefined;},
  2599. formatNoMatches: function () { return "No matches found"; },
  2600. formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); },
  2601. formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
  2602. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
  2603. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  2604. formatSearching: function () { return "Searching..."; },
  2605. minimumResultsForSearch: 0,
  2606. minimumInputLength: 0,
  2607. maximumInputLength: null,
  2608. maximumSelectionSize: 0,
  2609. id: function (e) { return e.id; },
  2610. matcher: function(term, text) {
  2611. return (''+text).toUpperCase().indexOf((''+term).toUpperCase()) >= 0;
  2612. },
  2613. separator: ",",
  2614. tokenSeparators: [],
  2615. tokenizer: defaultTokenizer,
  2616. escapeMarkup: defaultEscapeMarkup,
  2617. blurOnChange: false,
  2618. selectOnBlur: false,
  2619. adaptContainerCssClass: function(c) { return c; },
  2620. adaptDropdownCssClass: function(c) { return null; }
  2621. };
  2622. $.fn.select2.ajaxDefaults = {
  2623. transport: $.ajax,
  2624. params: {
  2625. type: "GET",
  2626. cache: false,
  2627. dataType: "json"
  2628. }
  2629. };
  2630. // exports
  2631. window.Select2 = {
  2632. query: {
  2633. ajax: ajax,
  2634. local: local,
  2635. tags: tags
  2636. }, util: {
  2637. debounce: debounce,
  2638. markMatch: markMatch,
  2639. escapeMarkup: defaultEscapeMarkup
  2640. }, "class": {
  2641. "abstract": AbstractSelect2,
  2642. "single": SingleSelect2,
  2643. "multi": MultiSelect2
  2644. }
  2645. };
  2646. }(jQuery));