select2.js 87 KB

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