select2.js 101 KB

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