select2.js 113 KB

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