select2.js 118 KB

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