select2.js 96 KB

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