select2.js 100 KB

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