select2.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670
  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 ($, undefined) {
  12. "use strict";
  13. /*global document, window, jQuery, console */
  14. if (window.Select2 !== undefined) {
  15. return;
  16. }
  17. var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid;
  18. KEY = {
  19. TAB: 9,
  20. ENTER: 13,
  21. ESC: 27,
  22. SPACE: 32,
  23. LEFT: 37,
  24. UP: 38,
  25. RIGHT: 39,
  26. DOWN: 40,
  27. SHIFT: 16,
  28. CTRL: 17,
  29. ALT: 18,
  30. PAGE_UP: 33,
  31. PAGE_DOWN: 34,
  32. HOME: 36,
  33. END: 35,
  34. BACKSPACE: 8,
  35. DELETE: 46,
  36. isArrow: function (k) {
  37. k = k.which ? k.which : k;
  38. switch (k) {
  39. case KEY.LEFT:
  40. case KEY.RIGHT:
  41. case KEY.UP:
  42. case KEY.DOWN:
  43. return true;
  44. }
  45. return false;
  46. },
  47. isControl: function (k) {
  48. k = k.which ? k.which : k;
  49. switch (k) {
  50. case KEY.SHIFT:
  51. case KEY.CTRL:
  52. case KEY.ALT:
  53. return true;
  54. }
  55. return false;
  56. },
  57. isFunctionKey: function (k) {
  58. k = k.which ? k.which : k;
  59. return k >= 112 && k <= 123;
  60. }
  61. };
  62. nextUid=(function() { var counter=1; return function() { return counter++; }}());
  63. function indexOf(value, array) {
  64. var i = 0, l = array.length, v;
  65. if (typeof value == 'undefined') {
  66. return -1;
  67. }
  68. if (value.constructor === String) {
  69. for (; i < l; i = i + 1) if (value.localeCompare(array[i]) === 0) return i;
  70. } else {
  71. for (; i < l; i = i + 1) {
  72. v = array[i];
  73. if (v.constructor === String) {
  74. if (v.localeCompare(value) === 0) return i;
  75. } else {
  76. if (v === value) return i;
  77. }
  78. }
  79. }
  80. return -1;
  81. }
  82. /**
  83. * Compares equality of a and b taking into account that a and b may be strings, in which case localCompare is used
  84. * @param a
  85. * @param b
  86. */
  87. function equal(a, b) {
  88. if (a === b) return true;
  89. if (a === undefined || b === undefined) return false;
  90. if (a === null || b === null) return false;
  91. if (a.constructor === String) return a.localeCompare(b) === 0;
  92. if (b.constructor === String) return b.localeCompare(a) === 0;
  93. return false;
  94. }
  95. /**
  96. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  97. * strings
  98. * @param string
  99. * @param separator
  100. */
  101. function splitVal(string, separator) {
  102. var val, i, l;
  103. if (string === null || string.length < 1) return [];
  104. val = string.split(separator);
  105. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  106. return val;
  107. }
  108. function getSideBorderPadding(element) {
  109. return element.outerWidth() - element.width();
  110. }
  111. function installKeyUpChangeEvent(element) {
  112. element.bind("keydown", function () {
  113. element.data("keyup-change-value", element.val());
  114. });
  115. element.bind("keyup", function () {
  116. if (element.val() !== element.data("keyup-change-value")) {
  117. element.trigger("keyup-change");
  118. }
  119. });
  120. }
  121. /**
  122. * filters mouse events so an event is fired only if the mouse moved.
  123. *
  124. * filters out mouse events that occur when mouse is stationary but
  125. * the elements under the pointer are scrolled.
  126. */
  127. $(document).delegate("*", "mousemove", function (e) {
  128. $(document).data("select2-lastpos", {x: e.pageX, y: e.pageY});
  129. });
  130. function installFilteredMouseMove(element) {
  131. element.bind("mousemove", function (e) {
  132. var lastpos = $(document).data("select2-lastpos");
  133. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  134. $(e.target).trigger("mousemove-filtered", e);
  135. }
  136. });
  137. }
  138. /**
  139. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  140. * within the last quietMillis milliseconds.
  141. *
  142. * @param quietMillis number of milliseconds to wait before invoking fn
  143. * @param fn function to be debounced
  144. * @return debounced version of fn
  145. */
  146. function debounce(quietMillis, fn) {
  147. var timeout;
  148. return function () {
  149. window.clearTimeout(timeout);
  150. timeout = window.setTimeout(fn, quietMillis);
  151. };
  152. }
  153. function installDebouncedScroll(threshold, element) {
  154. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  155. element.bind("scroll", function (e) {
  156. if (indexOf(e.target, element.get()) >= 0) notify(e);
  157. });
  158. }
  159. function killEvent(event) {
  160. event.preventDefault();
  161. event.stopPropagation();
  162. }
  163. function measureTextWidth(e) {
  164. var sizer, width;
  165. sizer = $("<div></div>").css({
  166. position: "absolute",
  167. left: "-1000px",
  168. top: "-1000px",
  169. display: "none",
  170. fontSize: e.css("fontSize"),
  171. fontFamily: e.css("fontFamily"),
  172. fontStyle: e.css("fontStyle"),
  173. fontWeight: e.css("fontWeight"),
  174. letterSpacing: e.css("letterSpacing"),
  175. textTransform: e.css("textTransform"),
  176. whiteSpace: "nowrap"
  177. });
  178. sizer.text(e.val());
  179. $("body").append(sizer);
  180. width = sizer.width();
  181. sizer.remove();
  182. return width;
  183. }
  184. /**
  185. * Produces an ajax-based query function
  186. *
  187. * @param options object containing configuration paramters
  188. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  189. * @param options.url url for the data
  190. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  191. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
  192. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  193. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  194. * The expected format is an object containing the following keys:
  195. * results array of objects that will be used as choices
  196. * more (optional) boolean indicating whether there are more results available
  197. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  198. */
  199. function ajax(options) {
  200. var timeout, // current scheduled but not yet executed request
  201. requestSequence = 0, // sequence used to drop out-of-order responses
  202. handler = null,
  203. quietMillis = options.quietMillis || 100;
  204. return function (query) {
  205. window.clearTimeout(timeout);
  206. timeout = window.setTimeout(function () {
  207. requestSequence += 1; // increment the sequence
  208. var requestNumber = requestSequence, // this request's sequence number
  209. data = options.data, // ajax data function
  210. transport = options.transport || $.ajax;
  211. data = data.call(this, query.term, query.page, query.context);
  212. if( null !== handler){
  213. handler.abort();
  214. }
  215. handler = transport.call(null, {
  216. url: options.url,
  217. dataType: options.dataType,
  218. data: data,
  219. success: function (data) {
  220. if (requestNumber < requestSequence) {
  221. return;
  222. }
  223. // TODO 3.0 - replace query.page with query so users have access to term, page, etc.
  224. var results = options.results(data, query.page);
  225. self.context = results.context;
  226. query.callback(results);
  227. }
  228. });
  229. }, quietMillis);
  230. };
  231. }
  232. /**
  233. * Produces a query function that works with a local array
  234. *
  235. * @param options object containing configuration parameters. The options parameter can either be an array or an
  236. * object.
  237. *
  238. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  239. *
  240. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  241. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  242. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  243. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  244. * the text.
  245. */
  246. function local(options) {
  247. var data = options, // data elements
  248. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  249. if (!$.isArray(data)) {
  250. text = data.text;
  251. // if text is not a function we assume it to be a key name
  252. if (!$.isFunction(text)) text = function (item) { return item[data.text]; };
  253. data = data.results;
  254. }
  255. return function (query) {
  256. var t = query.term, filtered = {};
  257. if (t === "") {
  258. query.callback({results: data});
  259. return;
  260. }
  261. filtered.results = $(data)
  262. .filter(function () {return query.matcher(t, text(this));})
  263. .get();
  264. query.callback(filtered);
  265. };
  266. }
  267. // TODO javadoc
  268. function tags(data) {
  269. // TODO even for a function we should probably return a wrapper that does the same object/string check as
  270. // the function for arrays. otherwise only functions that return objects are supported.
  271. if ($.isFunction(data)) {
  272. return data;
  273. }
  274. // if not a function we assume it to be an array
  275. return function (query) {
  276. var t = query.term, filtered = {results: []};
  277. $(data).each(function () {
  278. var isObject = this.text !== undefined,
  279. text = isObject ? this.text : this;
  280. if (t === "" || query.matcher(t, text)) {
  281. filtered.results.push(isObject ? this : {id: this, text: this});
  282. }
  283. });
  284. query.callback(filtered);
  285. };
  286. }
  287. /**
  288. * blurs any Select2 container that has focus when an element outside them was clicked or received focus
  289. */
  290. $(document).ready(function () {
  291. $(document).delegate("*", "mousedown focusin touchend", function (e) {
  292. var target = $(e.target).closest("div.select2-container").get(0);
  293. if (target) {
  294. $(document).find("div.select2-container-active").each(function () {
  295. if (this !== target) $(this).data("select2").blur();
  296. });
  297. } else {
  298. target = $(e.target).closest("div.select2-drop").get(0);
  299. $(document).find("div.select2-drop-active").each(function () {
  300. if (this !== target) $(this).data("select2").blur();
  301. });
  302. }
  303. });
  304. });
  305. /**
  306. * Creates a new class
  307. *
  308. * @param superClass
  309. * @param methods
  310. */
  311. function clazz(SuperClass, methods) {
  312. var constructor = function () {};
  313. constructor.prototype = new SuperClass;
  314. constructor.prototype.constructor = constructor;
  315. constructor.prototype.parent = SuperClass.prototype;
  316. constructor.prototype = $.extend(constructor.prototype, methods);
  317. return constructor;
  318. }
  319. AbstractSelect2 = clazz(Object, {
  320. bind: function (func) {
  321. var self = this;
  322. return function () {
  323. func.apply(self, arguments);
  324. };
  325. },
  326. init: function (opts) {
  327. var results, search, resultsSelector = ".select2-results";
  328. // prepare options
  329. this.opts = opts = this.prepareOpts(opts);
  330. this.id=opts.id;
  331. // destroy if called on an existing component
  332. if (opts.element.data("select2") !== undefined &&
  333. opts.element.data("select2") !== null) {
  334. this.destroy();
  335. }
  336. this.enabled=true;
  337. this.container = this.createContainer();
  338. if (opts.element.attr("class") !== undefined) {
  339. this.container.addClass(opts.element.attr("class"));
  340. }
  341. // swap container for the element
  342. this.opts.element
  343. .data("select2", this)
  344. .hide()
  345. .after(this.container);
  346. this.container.data("select2", this);
  347. this.dropdown = this.container.find(".select2-drop");
  348. this.dropdown.data("select2", this);
  349. this.results = results = this.container.find(resultsSelector);
  350. this.search = search = this.container.find("input[type=text]");
  351. this.resultsPage = 0;
  352. this.context = null;
  353. // initialize the container
  354. this.initContainer();
  355. installFilteredMouseMove(this.results);
  356. this.dropdown.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
  357. installDebouncedScroll(80, this.results);
  358. this.dropdown.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  359. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  360. if ($.fn.mousewheel) {
  361. results.mousewheel(function (e, delta, deltaX, deltaY) {
  362. var top = results.scrollTop(), height;
  363. if (deltaY > 0 && top - deltaY <= 0) {
  364. results.scrollTop(0);
  365. killEvent(e);
  366. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  367. results.scrollTop(results.get(0).scrollHeight - results.height());
  368. killEvent(e);
  369. }
  370. });
  371. }
  372. installKeyUpChangeEvent(search);
  373. search.bind("keyup-change", this.bind(this.updateResults));
  374. search.bind("focus", function () { search.addClass("select2-focused");});
  375. search.bind("blur", function () { search.removeClass("select2-focused");});
  376. this.dropdown.delegate(resultsSelector, "click", this.bind(function (e) {
  377. if ($(e.target).closest(".select2-result:not(.select2-disabled)").length > 0) {
  378. this.highlightUnderEvent(e);
  379. this.selectHighlighted(e);
  380. } else {
  381. killEvent(e);
  382. this.focusSearch();
  383. }
  384. }));
  385. if ($.isFunction(this.opts.initSelection)) {
  386. // initialize selection based on the current value of the source element
  387. this.initSelection();
  388. // if the user has provided a function that can set selection based on the value of the source element
  389. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  390. this.monitorSource();
  391. }
  392. if (opts.element.is(":disabled")) this.disable();
  393. },
  394. destroy: function () {
  395. var select2 = this.opts.element.data("select2");
  396. if (select2 !== undefined) {
  397. select2.container.remove();
  398. select2.dropdown.remove();
  399. select2.opts.element
  400. .removeData("select2")
  401. .unbind(".select2")
  402. .show();
  403. }
  404. },
  405. prepareOpts: function (opts) {
  406. var element, select, idKey;
  407. element = opts.element;
  408. if (element.get(0).tagName.toLowerCase() === "select") {
  409. this.select = select = opts.element;
  410. }
  411. if (select) {
  412. // these options are not allowed when attached to a select because they are picked up off the element itself
  413. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  414. if (this in opts) {
  415. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  416. }
  417. });
  418. }
  419. opts = $.extend({}, {
  420. populateResults: function(container, results) {
  421. var uidToData={}, populate, markup=[], uid, data, result, children;
  422. populate=function(results, depth) {
  423. var i, l, uid, result, selectable, compound;
  424. for (i = 0, l = results.length; i < l; i = i + 1) {
  425. result=results[i];
  426. selectable=("id" in result); // TODO switch to id() function
  427. compound=("children" in result) && result.children.length > 0;
  428. markup.push("<li class='select2-result-depth-"+depth);
  429. if (!selectable) { markup.push(" select2-result-unselectable"); } else { markup.push(" select2-result");}
  430. if (compound) { markup.push(" select2-result-with-children"); }
  431. markup.push("'");
  432. if (selectable) {
  433. uid=nextUid();
  434. markup.push(" id='select2-result-"+uid+"'");
  435. uidToData[uid]=result;
  436. }
  437. markup.push("><div class='select2-result-label'>"+opts.formatResult(result)+"</div>");
  438. if (compound) {
  439. markup.push("<ul class='select2-result-sub'>");
  440. populate(result.children, depth + 1);
  441. markup.push("</ul>");
  442. }
  443. markup.push("</li>");
  444. }
  445. };
  446. populate(results, 0);
  447. children=container.children();
  448. if (children.length==0) {
  449. container.html(markup.join(""));
  450. } else {
  451. $(children[children.length-1]).append(markup.join(""));
  452. }
  453. for (uid in uidToData) {
  454. $("#select2-result-"+uid).data("select2-data", uidToData[uid]);
  455. }
  456. },
  457. formatResult: function(result) {
  458. return result.text;
  459. },
  460. formatSelection: function (data) {
  461. if (data.fullText) {
  462. return data.fullText;
  463. } else {
  464. return data.text;
  465. }
  466. },
  467. formatNoMatches: function () { return "No matches found"; },
  468. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  469. minimumResultsForSearch: 0,
  470. minimumInputLength: 0,
  471. id: function (e) { return e.id; },
  472. matcher: function(term, text) {
  473. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  474. }
  475. }, opts);
  476. if (typeof(opts.id) !== "function") {
  477. idKey = opts.id;
  478. opts.id = function (e) { return e[idKey]; };
  479. }
  480. if (select) {
  481. opts.query = this.bind(function (query) {
  482. var data = { results: [], more: false },
  483. term = query.term,
  484. process;
  485. process=function(element, collection) {
  486. var group;
  487. if (element.is("option")) {
  488. if (query.matcher(term, element.text())) {
  489. collection.push({id:element.attr("value"), text:element.text()});
  490. }
  491. } else if (element.is("optgroup")) {
  492. group={text:element.attr("label"), children:[]};
  493. element.children().each(function() { process($(this), group.children); });
  494. if (group.children.length>0) {
  495. collection.push(group);
  496. }
  497. }
  498. };
  499. element.children().each(function() { process($(this), data.results); });
  500. query.callback(data);
  501. });
  502. // this is needed because inside val() we construct choices from options and there id is hardcoded
  503. opts.id=function(e) { return e.id; };
  504. } else {
  505. if (!("query" in opts)) {
  506. if ("ajax" in opts) {
  507. opts.query = ajax(opts.ajax);
  508. } else if ("data" in opts) {
  509. opts.query = local(opts.data);
  510. } else if ("tags" in opts) {
  511. opts.query = tags(opts.tags);
  512. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  513. opts.initSelection = function (element) {
  514. var data = [];
  515. $(splitVal(element.val(), ",")).each(function () {
  516. data.push({id: this, text: this});
  517. });
  518. return data;
  519. };
  520. }
  521. }
  522. }
  523. if (typeof(opts.query) !== "function") {
  524. throw "query function not defined for Select2 " + opts.element.attr("id");
  525. }
  526. return opts;
  527. },
  528. /**
  529. * Monitor the original element for changes and update select2 accordingly
  530. */
  531. monitorSource: function () {
  532. this.opts.element.bind("change.select2", this.bind(function (e) {
  533. if (this.opts.element.data("select2-change-triggered") !== true) {
  534. this.initSelection();
  535. }
  536. }));
  537. },
  538. /**
  539. * Triggers the change event on the source element
  540. */
  541. triggerChange: function () {
  542. // Prevents recursive triggering
  543. this.opts.element.data("select2-change-triggered", true);
  544. this.opts.element.trigger("change");
  545. this.opts.element.data("select2-change-triggered", false);
  546. },
  547. enable: function() {
  548. if (this.enabled) return;
  549. this.enabled=true;
  550. this.container.removeClass("select2-container-disabled");
  551. },
  552. disable: function() {
  553. if (!this.enabled) return;
  554. this.close();
  555. this.enabled=false;
  556. this.container.addClass("select2-container-disabled");
  557. },
  558. opened: function () {
  559. return this.container.hasClass("select2-dropdown-open");
  560. },
  561. positionDropdown: function() {
  562. var offset = this.container.offset();
  563. var height = this.container.outerHeight();
  564. var width = this.container.outerWidth();
  565. this.dropdown.css({
  566. top: offset.top + height,
  567. left: offset.left,
  568. width: width
  569. });
  570. },
  571. open: function () {
  572. if (this.opened()) return;
  573. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  574. this.dropdown.detach().appendTo('body').addClass("select2-drop-active");
  575. this.positionDropdown();
  576. this.updateResults(true);
  577. this.dropdown.show();
  578. this.ensureHighlightVisible();
  579. this.focusSearch();
  580. },
  581. close: function () {
  582. if (!this.opened()) return;
  583. this.dropdown.hide();
  584. this.container.removeClass("select2-dropdown-open");
  585. this.results.empty();
  586. this.clearSearch();
  587. },
  588. clearSearch: function () {
  589. },
  590. ensureHighlightVisible: function () {
  591. var results = this.results, children, index, child, hb, rb, y, more;
  592. children = results.find(".select2-result");
  593. index = this.highlight();
  594. if (index < 0) return;
  595. child = $(children[index]);
  596. hb = child.offset().top + child.outerHeight();
  597. // if this is the last child lets also make sure select2-more-results is visible
  598. if (index === children.length - 1) {
  599. more = results.find("li.select2-more-results");
  600. if (more.length > 0) {
  601. hb = more.offset().top + more.outerHeight();
  602. }
  603. }
  604. rb = results.offset().top + results.outerHeight();
  605. if (hb > rb) {
  606. results.scrollTop(results.scrollTop() + (hb - rb));
  607. }
  608. y = child.offset().top - results.offset().top;
  609. // make sure the top of the element is visible
  610. if (y < 0) {
  611. results.scrollTop(results.scrollTop() + y); // y is negative
  612. }
  613. },
  614. moveHighlight: function (delta) {
  615. var choices = this.results.find(".select2-result"),
  616. index = this.highlight();
  617. while (index > -1 && index < choices.length) {
  618. index += delta;
  619. if (!$(choices[index]).hasClass("select2-disabled")) {
  620. this.highlight(index);
  621. break;
  622. }
  623. }
  624. },
  625. highlight: function (index) {
  626. var choices = this.results.find(".select2-result .select2-result-label");
  627. if (arguments.length === 0) {
  628. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  629. }
  630. if (index >= choices.length) index = choices.length - 1;
  631. if (index < 0) index = 0;
  632. if ($(choices[index]).parent().is('.select2-result-unselectable')) {
  633. return;
  634. }
  635. choices.removeClass("select2-highlighted");
  636. $(choices[index]).addClass("select2-highlighted");
  637. this.ensureHighlightVisible();
  638. if (this.opened()) this.focusSearch();
  639. },
  640. highlightUnderEvent: function (event) {
  641. var el = $(event.target).closest(".select2-result");
  642. var choices = this.results.find('.select2-result');
  643. if (el.length > 0) {
  644. this.highlight(choices.index(el));
  645. }
  646. },
  647. loadMoreIfNeeded: function () {
  648. var results = this.results,
  649. more = results.find("li.select2-more-results"),
  650. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  651. offset = -1, // index of first element without data
  652. page = this.resultsPage + 1,
  653. self=this;
  654. if (more.length === 0) return;
  655. below = more.offset().top - results.offset().top - results.height();
  656. if (below <= 0) {
  657. more.addClass("select2-active");
  658. this.opts.query({
  659. term: this.search.val(),
  660. page: page,
  661. context: this.context,
  662. matcher: this.opts.matcher,
  663. callback: this.bind(function (data) {
  664. console.log("load more callback", data);
  665. self.opts.populateResults(results, data.results);
  666. if (data.more===true) {
  667. more.detach();
  668. results.children().filter(":last").append(more);
  669. more.removeClass("select2-active");
  670. } else {
  671. more.remove();
  672. }
  673. self.resultsPage = page;
  674. })});
  675. }
  676. },
  677. /**
  678. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  679. */
  680. updateResults: function (initial) {
  681. var search = this.search, results = this.results, opts = this.opts, self=this;
  682. // if the search is currently hidden we do not alter the results
  683. if (initial !== true && this.showSearchInput === false) {
  684. return;
  685. }
  686. search.addClass("select2-active");
  687. function postRender() {
  688. results.scrollTop(0);
  689. search.removeClass("select2-active");
  690. }
  691. function render(html) {
  692. results.html(html);
  693. postRender();
  694. }
  695. if (search.val().length < opts.minimumInputLength) {
  696. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  697. return;
  698. }
  699. this.resultsPage = 1;
  700. opts.query({
  701. term: search.val(),
  702. page: this.resultsPage,
  703. context: null,
  704. matcher: opts.matcher,
  705. callback: this.bind(function (data) {
  706. var def; // default choice
  707. // create a default choice and prepend it to the list
  708. if (this.opts.createSearchChoice && search.val() !== "") {
  709. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  710. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  711. if ($(data.results).filter(
  712. function () {
  713. return equal(self.id(this), self.id(def));
  714. }).length === 0) {
  715. data.results.unshift(def);
  716. }
  717. }
  718. }
  719. if (data.results.length === 0) {
  720. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  721. return;
  722. }
  723. results.empty();
  724. self.opts.populateResults(results, data.results);
  725. postRender();
  726. if (data.more === true) {
  727. results.children().filter(":last").append("<li class='select2-more-results'>Loading more results...</li>");
  728. }
  729. this.postprocessResults(data, initial);
  730. })});
  731. },
  732. cancel: function () {
  733. this.close();
  734. },
  735. blur: function () {
  736. /* we do this in a timeout so that current event processing can complete before this code is executed.
  737. this allows tab index to be preserved even if this code blurs the textfield */
  738. window.setTimeout(this.bind(function () {
  739. this.close();
  740. this.container.removeClass("select2-container-active");
  741. this.dropdown.removeClass("select2-drop-active");
  742. this.clearSearch();
  743. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  744. this.search.blur();
  745. }), 10);
  746. },
  747. focusSearch: function () {
  748. /* we do this in a timeout so that current event processing can complete before this code is executed.
  749. this makes sure the search field is focussed even if the current event would blur it */
  750. window.setTimeout(this.bind(function () {
  751. this.search.focus();
  752. }), 10);
  753. },
  754. selectHighlighted: function () {
  755. var data = this.results.find(".select2-highlighted").not(".select2-disabled").closest('.select2-result').not('.select2-result-unselectable').data("select2-data");
  756. if (data) {
  757. this.onSelect(data);
  758. }
  759. },
  760. getPlaceholder: function () {
  761. return this.opts.element.attr("placeholder") || this.opts.element.data("placeholder") || this.opts.placeholder;
  762. },
  763. /**
  764. * Get the desired width for the container element. This is
  765. * derived first from option `width` passed to select2, then
  766. * the inline 'style' on the original element, and finally
  767. * falls back to the jQuery calculated element width.
  768. *
  769. * @returns The width string (with units) for the container.
  770. */
  771. getContainerWidth: function () {
  772. var style, attrs, matches, i, l;
  773. if (this.opts.width !== undefined)
  774. return this.opts.width;
  775. style = this.opts.element.attr('style');
  776. if (style !== undefined) {
  777. attrs = style.split(';');
  778. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  779. matches = attrs[i].replace(/\s/g, '')
  780. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  781. if (matches !== null && matches.length >= 1)
  782. return matches[1];
  783. }
  784. }
  785. return this.opts.element.width() + 'px';
  786. }
  787. });
  788. SingleSelect2 = clazz(AbstractSelect2, {
  789. createContainer: function () {
  790. return $("<div></div>", {
  791. "class": "select2-container",
  792. "style": "width: " + this.getContainerWidth()
  793. }).html([
  794. " <a href='javascript:void(0)' class='select2-choice'>",
  795. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  796. " <div><b></b></div>" ,
  797. "</a>",
  798. " <div class='select2-drop' style='display:none;'>" ,
  799. " <div class='select2-search'>" ,
  800. " <input type='text' autocomplete='off'/>" ,
  801. " </div>" ,
  802. " <ul class='select2-results'>" ,
  803. " </ul>" ,
  804. "</div>"].join(""));
  805. },
  806. open: function () {
  807. if (this.opened()) return;
  808. this.parent.open.apply(this, arguments);
  809. },
  810. close: function () {
  811. if (!this.opened()) return;
  812. this.parent.close.apply(this, arguments);
  813. },
  814. focus: function () {
  815. this.close();
  816. this.selection.focus();
  817. },
  818. isFocused: function () {
  819. return this.selection.is(":focus");
  820. },
  821. cancel: function () {
  822. this.parent.cancel.apply(this, arguments);
  823. this.selection.focus();
  824. },
  825. initContainer: function () {
  826. var selection,
  827. container = this.container,
  828. dropdown = this.dropdown,
  829. containers = $([this.container.get(0), this.dropdown.get(0)]),
  830. clickingInside = false,
  831. selector = ".select2-choice";
  832. this.selection = selection = container.find(selector);
  833. this.search.bind("keydown", this.bind(function (e) {
  834. switch (e.which) {
  835. case KEY.UP:
  836. case KEY.DOWN:
  837. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  838. killEvent(e);
  839. return;
  840. case KEY.TAB:
  841. case KEY.ENTER:
  842. this.selectHighlighted();
  843. killEvent(e);
  844. return;
  845. case KEY.ESC:
  846. this.cancel(e);
  847. e.preventDefault();
  848. return;
  849. }
  850. }));
  851. containers.delegate(selector, "click", this.bind(function (e) {
  852. clickingInside = true;
  853. if (this.opened()) {
  854. this.close();
  855. selection.focus();
  856. } else if (this.enabled) {
  857. this.open();
  858. }
  859. e.preventDefault();
  860. clickingInside = false;
  861. }));
  862. containers.delegate(selector, "keydown", this.bind(function (e) {
  863. if (!this.enabled || e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  864. return;
  865. }
  866. this.open();
  867. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN || e.which === KEY.SPACE) {
  868. // prevent the page from scrolling
  869. killEvent(e);
  870. }
  871. if (e.which === KEY.ENTER) {
  872. // do not propagate the event otherwise we open, and propagate enter which closes
  873. killEvent(e);
  874. }
  875. }));
  876. containers.delegate(selector, "focus", function () { if (this.enabled) { containerGroup.addClass("select2-container-active"); dropdown.addClass("select2-drop-active"); }});
  877. containers.delegate(selector, "blur", this.bind(function () {
  878. if (clickingInside) return;
  879. if (!this.opened()) this.blur();
  880. }));
  881. selection.delegate("abbr", "click", this.bind(function (e) {
  882. if (!this.enabled) return;
  883. this.val("");
  884. killEvent(e);
  885. this.close();
  886. this.triggerChange();
  887. }));
  888. this.setPlaceholder();
  889. },
  890. /**
  891. * Sets selection based on source element's value
  892. */
  893. initSelection: function () {
  894. var selected;
  895. if (this.opts.element.val() === "") {
  896. this.updateSelection({id: "", text: ""});
  897. } else {
  898. selected = this.opts.initSelection.call(null, this.opts.element);
  899. if (selected !== undefined && selected !== null) {
  900. this.updateSelection(selected);
  901. }
  902. }
  903. this.close();
  904. this.setPlaceholder();
  905. },
  906. prepareOpts: function () {
  907. var opts = this.parent.prepareOpts.apply(this, arguments);
  908. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  909. // install sthe selection initializer
  910. opts.initSelection = function (element) {
  911. var selected = element.find(":selected");
  912. // a single select box always has a value, no need to null check 'selected'
  913. return {id: selected.attr("value"), text: selected.text()};
  914. };
  915. }
  916. return opts;
  917. },
  918. setPlaceholder: function () {
  919. var placeholder = this.getPlaceholder();
  920. if (this.opts.element.val() === "" && placeholder !== undefined) {
  921. // check for a first blank option if attached to a select
  922. if (this.select && this.select.find("option:first").text() !== "") return;
  923. if (typeof(placeholder) === "object") {
  924. this.updateSelection(placeholder);
  925. } else {
  926. this.selection.find("span").html(placeholder);
  927. }
  928. this.selection.addClass("select2-default");
  929. this.selection.find("abbr").hide();
  930. }
  931. },
  932. postprocessResults: function (data, initial) {
  933. var selected = 0, self = this, showSearchInput = true;
  934. // find the selected element in the result list
  935. this.results.find(".select2-result").each(function (i) {
  936. if (equal(self.id($(this).data("select2-data")), self.opts.element.val())) {
  937. selected = i;
  938. return false;
  939. }
  940. });
  941. // and highlight it
  942. this.highlight(selected);
  943. // hide the search box if this is the first we got the results and there are a few of them
  944. if (initial === true) {
  945. showSearchInput = this.showSearchInput = data.results.length >= this.opts.minimumResultsForSearch;
  946. this.container.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  947. //add "select2-with-searchbox" to the container if search box is shown
  948. this.container[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  949. }
  950. },
  951. onSelect: function (data) {
  952. var old = this.opts.element.val();
  953. this.opts.element.val(this.id(data));
  954. this.updateSelection(data);
  955. this.close();
  956. this.selection.focus();
  957. if (!equal(old, this.id(data))) { this.triggerChange(); }
  958. },
  959. updateSelection: function (data) {
  960. this.selection
  961. .find("span")
  962. .html(this.opts.formatSelection(data));
  963. this.selection.removeClass("select2-default");
  964. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  965. this.selection.find("abbr").show();
  966. }
  967. },
  968. val: function () {
  969. var val, data = null;
  970. if (arguments.length === 0) {
  971. return this.opts.element.val();
  972. }
  973. val = arguments[0];
  974. if (this.select) {
  975. // val is an id
  976. this.select
  977. .val(val)
  978. .find(":selected").each(function () {
  979. data = {id: $(this).attr("value"), text: $(this).text()};
  980. return false;
  981. });
  982. this.updateSelection(data);
  983. } else {
  984. // val is an object. !val is true for [undefined,null,'']
  985. this.opts.element.val(!val ? "" : this.id(val));
  986. this.updateSelection(val);
  987. }
  988. this.setPlaceholder();
  989. },
  990. clearSearch: function () {
  991. this.search.val("");
  992. }
  993. });
  994. MultiSelect2 = clazz(AbstractSelect2, {
  995. createContainer: function () {
  996. return $("<div></div>", {
  997. "class": "select2-container select2-container-multi",
  998. "style": "width: " + this.getContainerWidth()
  999. }).html([
  1000. " <ul class='select2-choices'>",
  1001. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1002. " <li class='select2-search-field'>" ,
  1003. " <input type='text' autocomplete='off' style='width: 25px;'>" ,
  1004. " </li>" ,
  1005. "</ul>" ,
  1006. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1007. " <ul class='select2-results'>" ,
  1008. " </ul>" ,
  1009. "</div>"].join(""));
  1010. },
  1011. prepareOpts: function () {
  1012. var opts = this.parent.prepareOpts.apply(this, arguments);
  1013. opts = $.extend({}, {
  1014. closeOnSelect: true
  1015. }, opts);
  1016. // TODO validate placeholder is a string if specified
  1017. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1018. // install sthe selection initializer
  1019. opts.initSelection = function (element) {
  1020. var data = [];
  1021. element.find(":selected").each(function () {
  1022. data.push({id: $(this).attr("value"), text: $(this).text()});
  1023. });
  1024. return data;
  1025. };
  1026. }
  1027. return opts;
  1028. },
  1029. initContainer: function () {
  1030. var selector = ".select2-choices", selection;
  1031. this.searchContainer = this.container.find(".select2-search-field");
  1032. this.selection = selection = this.container.find(selector);
  1033. this.search.bind("keydown", this.bind(function (e) {
  1034. if (!this.enabled) return;
  1035. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1036. this.close();
  1037. var choices,
  1038. selected = selection.find(".select2-search-choice-focus");
  1039. if (selected.length > 0) {
  1040. this.unselect(selected.first());
  1041. this.search.width(10);
  1042. killEvent(e);
  1043. return;
  1044. }
  1045. choices = selection.find(".select2-search-choice");
  1046. if (choices.length > 0) {
  1047. choices.last().addClass("select2-search-choice-focus");
  1048. }
  1049. } else {
  1050. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1051. }
  1052. if (this.opened()) {
  1053. switch (e.which) {
  1054. case KEY.UP:
  1055. case KEY.DOWN:
  1056. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1057. killEvent(e);
  1058. return;
  1059. case KEY.ENTER:
  1060. case KEY.TAB:
  1061. this.selectHighlighted();
  1062. killEvent(e);
  1063. return;
  1064. case KEY.ESC:
  1065. this.cancel(e);
  1066. e.preventDefault();
  1067. return;
  1068. }
  1069. }
  1070. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1071. return;
  1072. }
  1073. this.open();
  1074. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1075. // prevent the page from scrolling
  1076. killEvent(e);
  1077. }
  1078. }));
  1079. this.search.bind("keyup", this.bind(this.resizeSearch));
  1080. this.container.delegate(selector, "click", this.bind(function (e) {
  1081. if (!this.enabled) return;
  1082. this.open();
  1083. this.focusSearch();
  1084. e.preventDefault();
  1085. }));
  1086. this.container.delegate(selector, "focus", this.bind(function () {
  1087. if (!this.enabled) return;
  1088. this.container.addClass("select2-container-active");
  1089. this.dropdown.addClass("select2-drop-active");
  1090. this.clearPlaceholder();
  1091. }));
  1092. // set the placeholder if necessary
  1093. this.clearSearch();
  1094. },
  1095. enable: function() {
  1096. if (this.enabled) return;
  1097. this.parent.enable.apply(this, arguments);
  1098. this.search.show();
  1099. },
  1100. disable: function() {
  1101. if (!this.enabled) return;
  1102. this.parent.disable.apply(this, arguments);
  1103. this.search.hide();
  1104. },
  1105. initSelection: function () {
  1106. var data;
  1107. if (this.opts.element.val() === "") {
  1108. this.updateSelection([]);
  1109. }
  1110. if (this.select || this.opts.element.val() !== "") {
  1111. data = this.opts.initSelection.call(null, this.opts.element);
  1112. if (data !== undefined && data !== null) {
  1113. this.updateSelection(data);
  1114. }
  1115. }
  1116. this.close();
  1117. // set the placeholder if necessary
  1118. this.clearSearch();
  1119. },
  1120. clearSearch: function () {
  1121. var placeholder = this.getPlaceholder();
  1122. if (placeholder !== undefined
  1123. && this.getVal().length === 0
  1124. && this.search.hasClass("select2-focused") === false) {
  1125. this.search.val(placeholder).addClass("select2-default");
  1126. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1127. this.search.width(this.getContainerWidth());
  1128. } else {
  1129. this.search.val("").width(10);
  1130. }
  1131. },
  1132. clearPlaceholder: function () {
  1133. if (this.search.hasClass("select2-default")) {
  1134. this.search.val("").removeClass("select2-default");
  1135. }
  1136. },
  1137. open: function () {
  1138. if (this.opened()) return;
  1139. this.parent.open.apply(this, arguments);
  1140. this.resizeSearch();
  1141. this.focusSearch();
  1142. },
  1143. close: function () {
  1144. if (!this.opened()) return;
  1145. this.parent.close.apply(this, arguments);
  1146. },
  1147. focus: function () {
  1148. this.close();
  1149. this.search.focus();
  1150. },
  1151. isFocused: function () {
  1152. return this.search.hasClass("select2-focused");
  1153. },
  1154. updateSelection: function (data) {
  1155. var ids = [], filtered = [], self = this;
  1156. // filter out duplicates
  1157. $(data).each(function () {
  1158. if (indexOf(self.id(this), ids) < 0) {
  1159. ids.push(self.id(this));
  1160. filtered.push(this);
  1161. }
  1162. });
  1163. data = filtered;
  1164. this.selection.find(".select2-search-choice").remove();
  1165. $(data).each(function () {
  1166. self.addSelectedChoice(this);
  1167. });
  1168. self.postprocessResults();
  1169. },
  1170. onSelect: function (data) {
  1171. this.addSelectedChoice(data);
  1172. if (this.select) { this.postprocessResults(); }
  1173. if (this.opts.closeOnSelect) {
  1174. this.close();
  1175. this.search.width(10);
  1176. } else {
  1177. this.search.width(10);
  1178. this.resizeSearch();
  1179. }
  1180. // since its not possible to select an element that has already been
  1181. // added we do not need to check if this is a new element before firing change
  1182. this.triggerChange();
  1183. this.focusSearch();
  1184. },
  1185. cancel: function () {
  1186. this.close();
  1187. this.focusSearch();
  1188. },
  1189. addSelectedChoice: function (data) {
  1190. var choice,
  1191. id = this.id(data),
  1192. parts,
  1193. val = this.getVal();
  1194. parts = ["<li class='select2-search-choice'>",
  1195. this.opts.formatSelection(data),
  1196. "<a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>",
  1197. "</li>"
  1198. ];
  1199. choice = $(parts.join(""));
  1200. choice.find("a")
  1201. .bind("click dblclick", this.bind(function (e) {
  1202. if (!this.enabled) return;
  1203. this.unselect($(e.target));
  1204. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1205. killEvent(e);
  1206. this.close();
  1207. this.focusSearch();
  1208. })).bind("focus", this.bind(function () {
  1209. if (!this.enabled) return;
  1210. this.container.addClass("select2-container-active");
  1211. this.dropdown.addClass("select2-drop-active");
  1212. }));
  1213. choice.data("select2-data", data);
  1214. choice.insertBefore(this.searchContainer);
  1215. val.push(id);
  1216. this.setVal(val);
  1217. },
  1218. unselect: function (selected) {
  1219. var val = this.getVal(),
  1220. index;
  1221. selected = selected.closest(".select2-search-choice");
  1222. if (selected.length === 0) {
  1223. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1224. }
  1225. index = indexOf(this.id(selected.data("select2-data")), val);
  1226. if (index >= 0) {
  1227. val.splice(index, 1);
  1228. this.setVal(val);
  1229. if (this.select) this.postprocessResults();
  1230. }
  1231. selected.remove();
  1232. this.triggerChange();
  1233. },
  1234. postprocessResults: function () {
  1235. var val = this.getVal(),
  1236. choices = this.results.find(".select2-result"),
  1237. self = this;
  1238. choices.each(function () {
  1239. var choice = $(this), id = self.id(choice.data("select2-data"));
  1240. if (indexOf(id, val) >= 0) {
  1241. choice.addClass("select2-disabled");
  1242. } else {
  1243. choice.removeClass("select2-disabled");
  1244. }
  1245. });
  1246. choices.each(function (i) {
  1247. if (!$(this).hasClass("select2-disabled")) {
  1248. self.highlight(i);
  1249. return false;
  1250. }
  1251. });
  1252. },
  1253. resizeSearch: function () {
  1254. var minimumWidth, left, maxWidth, containerLeft, searchWidth;
  1255. minimumWidth = measureTextWidth(this.search) + 10;
  1256. left = this.search.offset().left;
  1257. maxWidth = this.selection.width();
  1258. containerLeft = this.selection.offset().left;
  1259. searchWidth = maxWidth - (left - containerLeft) - getSideBorderPadding(this.search);
  1260. if (searchWidth < minimumWidth) {
  1261. searchWidth = maxWidth - getSideBorderPadding(this.search);
  1262. }
  1263. if (searchWidth < 40) {
  1264. searchWidth = maxWidth - getSideBorderPadding(this.search);
  1265. }
  1266. this.search.width(searchWidth);
  1267. },
  1268. getVal: function () {
  1269. var val;
  1270. if (this.select) {
  1271. val = this.select.val();
  1272. return val === null ? [] : val;
  1273. } else {
  1274. val = this.opts.element.val();
  1275. return splitVal(val, ",");
  1276. }
  1277. },
  1278. setVal: function (val) {
  1279. var unique;
  1280. if (this.select) {
  1281. this.select.val(val);
  1282. } else {
  1283. unique = [];
  1284. // filter out duplicates
  1285. $(val).each(function () {
  1286. if (indexOf(this, unique) < 0) unique.push(this);
  1287. });
  1288. this.opts.element.val(unique.length === 0 ? "" : unique.join(","));
  1289. }
  1290. },
  1291. val: function () {
  1292. var val, data = [], self=this;
  1293. if (arguments.length === 0) {
  1294. return this.getVal();
  1295. }
  1296. val = arguments[0];
  1297. if (this.select) {
  1298. // val is a list of ids
  1299. this.setVal(val);
  1300. this.select.find(":selected").each(function () {
  1301. data.push({id: $(this).attr("value"), text: $(this).text()});
  1302. });
  1303. this.updateSelection(data);
  1304. } else {
  1305. val = (val === null) ? [] : val;
  1306. this.setVal(val);
  1307. // val is a list of objects
  1308. st
  1309. $(val).each(function () { data.push(self.id(this)); });
  1310. this.setVal(data);
  1311. this.updateSelection(val);
  1312. }
  1313. this.clearSearch();
  1314. },
  1315. onSortStart: function() {
  1316. if (this.select) {
  1317. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  1318. }
  1319. // collapse search field into 0 width so its container can be collapsed as well
  1320. this.search.width(0);
  1321. // hide the container
  1322. this.searchContainer.hide();
  1323. },
  1324. onSortEnd:function() {
  1325. var val=[], self=this;
  1326. // show search and move it to the end of the list
  1327. this.searchContainer.show();
  1328. // make sure the search container is the last item in the list
  1329. this.searchContainer.appendTo(this.searchContainer.parent());
  1330. // since we collapsed the width in dragStarteed, we resize it here
  1331. this.resizeSearch();
  1332. // update selection
  1333. this.selection.find(".select2-search-choice").each(function() {
  1334. val.push(self.opts.id($(this).data("select2-data")));
  1335. });
  1336. this.setVal(val);
  1337. this.triggerChange();
  1338. }
  1339. });
  1340. $.fn.select2 = function () {
  1341. var args = Array.prototype.slice.call(arguments, 0),
  1342. opts,
  1343. select2,
  1344. value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown"];
  1345. this.each(function () {
  1346. if (args.length === 0 || typeof(args[0]) === "object") {
  1347. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1348. opts.element = $(this);
  1349. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1350. multiple = opts.element.attr("multiple");
  1351. } else {
  1352. multiple = opts.multiple || false;
  1353. if ("tags" in opts) {opts.multiple = multiple = true;}
  1354. }
  1355. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1356. select2.init(opts);
  1357. } else if (typeof(args[0]) === "string") {
  1358. if (indexOf(args[0], allowedMethods) < 0) {
  1359. throw "Unknown method: " + args[0];
  1360. }
  1361. value = undefined;
  1362. select2 = $(this).data("select2");
  1363. if (select2 === undefined) return;
  1364. if (args[0] === "container") {
  1365. value=select2.container;
  1366. } else {
  1367. value = select2[args[0]].apply(select2, args.slice(1));
  1368. }
  1369. if (value !== undefined) {return false;}
  1370. } else {
  1371. throw "Invalid arguments to select2 plugin: " + args;
  1372. }
  1373. });
  1374. return (value === undefined) ? this : value;
  1375. };
  1376. // exports
  1377. window.Select2 = {
  1378. query: {
  1379. ajax: ajax,
  1380. local: local,
  1381. tags: tags
  1382. }, util: {
  1383. debounce: debounce
  1384. }, "class": {
  1385. "abstract": AbstractSelect2,
  1386. "single": SingleSelect2,
  1387. "multi": MultiSelect2
  1388. }
  1389. };
  1390. }(jQuery));