select2.js 86 KB

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