select2.js 85 KB

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