bootstrap-select.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. !function($) {
  2. var Selectpicker = function(element, options, e) {
  3. if (e ) {
  4. e.stopPropagation();
  5. e.preventDefault();
  6. }
  7. this.$element = $(element);
  8. this.$newElement = null;
  9. this.button = null;
  10. //Merge defaults, options and data-attributes to make our options
  11. this.options = $.extend({}, $.fn.selectpicker.defaults, this.$element.data(), typeof options == 'object' && options);
  12. //If we have no title yet, check the attribute 'title' (this is missed by jq as its not a data-attribute
  13. if(this.options.title==null)
  14. this.options.title = this.$element.attr('title');
  15. //Expose public methods
  16. this.val = Selectpicker.prototype.val;
  17. this.render = Selectpicker.prototype.render;
  18. this.init();
  19. };
  20. Selectpicker.prototype = {
  21. constructor: Selectpicker,
  22. init: function (e) {
  23. var _this = this;
  24. this.$element.hide();
  25. this.multiple = this.$element.prop('multiple');
  26. var classList = this.$element.attr('class') !== undefined ? this.$element.attr('class').split(/\s+/) : '';
  27. var id = this.$element.attr('id');
  28. this.$element.after( this.createView() );
  29. this.$newElement = this.$element.next('.select');
  30. var select = this.$newElement;
  31. var menu = this.$newElement.find('.dropdown-menu');
  32. var menuArrow = this.$newElement.find('.dropdown-arrow');
  33. var menuA = menu.find('li > a');
  34. var liHeight = select.addClass('open').find('.dropdown-menu li > a').outerHeight();
  35. select.removeClass('open');
  36. var divHeight = menu.find('li .divider').outerHeight(true);
  37. var selectOffset_top = this.$newElement.offset().top;
  38. var size = 0;
  39. var menuHeight = 0;
  40. var selectHeight = this.$newElement.outerHeight();
  41. this.button = this.$newElement.find('> button');
  42. if (id !== undefined) {
  43. this.button.attr('id', id);
  44. $('label[for="' + id + '"]').click(function(){ select.find('button#'+id).focus(); })
  45. }
  46. for (var i = 0; i < classList.length; i++) {
  47. if(classList[i] != 'selectpicker') {
  48. this.$newElement.addClass(classList[i]);
  49. }
  50. }
  51. //If we are multiple, then add the show-tick class by default
  52. if(this.multiple) {
  53. this.$newElement.addClass('select-multiple');
  54. }
  55. this.button.addClass(this.options.style);
  56. menu.addClass(this.options.menuStyle);
  57. menuArrow.addClass(function() {
  58. if (_this.options.menuStyle) {
  59. return _this.options.menuStyle.replace('dropdown-', 'dropdown-arrow-');
  60. }
  61. });
  62. this.checkDisabled();
  63. this.checkTabIndex();
  64. this.clickListener();
  65. var menuPadding = parseInt(menu.css('padding-top')) + parseInt(menu.css('padding-bottom')) + parseInt(menu.css('border-top-width')) + parseInt(menu.css('border-bottom-width'));
  66. if (this.options.size == 'auto') {
  67. function getSize() {
  68. var selectOffset_top_scroll = selectOffset_top - $(window).scrollTop();
  69. var windowHeight = $(window).innerHeight();
  70. var menuExtras = menuPadding + parseInt(menu.css('margin-top')) + parseInt(menu.css('margin-bottom')) + 2;
  71. var selectOffset_bot = windowHeight - selectOffset_top_scroll - selectHeight - menuExtras;
  72. menuHeight = selectOffset_bot;
  73. if (select.hasClass('dropup')) {
  74. menuHeight = selectOffset_top_scroll - menuExtras;
  75. }
  76. menu.css({'max-height' : menuHeight + 'px', 'overflow-y' : 'auto', 'min-height' : liHeight*3 + 'px'});
  77. }
  78. getSize();
  79. $(window).resize(getSize);
  80. $(window).scroll(getSize);
  81. if (window.MutationObserver) {
  82. new MutationObserver(getSize).observe(this.$element.get(0), {
  83. childList: true
  84. });
  85. } else {
  86. this.$element.bind('DOMNodeInserted', getSize);
  87. }
  88. } else if (this.options.size && this.options.size != 'auto' && menu.find('li').length > this.options.size) {
  89. var optIndex = menu.find("li > *").filter(':not(.divider)').slice(0,this.options.size).last().parent().index();
  90. var divLength = menu.find("li").slice(0,optIndex + 1).find('.divider').length;
  91. menuHeight = liHeight*this.options.size + divLength*divHeight + menuPadding;
  92. menu.css({'max-height' : menuHeight + 'px', 'overflow-y' : 'scroll'});
  93. }
  94. // Listen for updates to the DOM and re render... (Use Mutation Observer when availiable)
  95. if (window.MutationObserver) {
  96. new MutationObserver($.proxy(this.reloadLi, this)).observe(this.$element.get(0), {
  97. childList: true
  98. });
  99. } else {
  100. this.$element.bind('DOMNodeInserted', $.proxy(this.reloadLi, this));
  101. }
  102. this.render();
  103. },
  104. createDropdown: function() {
  105. var drop =
  106. "<div class='btn-group select'>" +
  107. "<button class='btn dropdown-toggle clearfix' data-toggle='dropdown'>" +
  108. "<span class='filter-option pull-left'></span>&nbsp;" +
  109. "<span class='caret'></span>" +
  110. "</button>" +
  111. "<span class='dropdown-arrow'></span>" +
  112. "<ul class='dropdown-menu' role='menu'>" +
  113. "</ul>" +
  114. "</div>";
  115. return $(drop);
  116. },
  117. createView: function() {
  118. var $drop = this.createDropdown();
  119. var $li = this.createLi();
  120. $drop.find('ul').append($li);
  121. return $drop;
  122. },
  123. reloadLi: function() {
  124. //Remove all children.
  125. this.destroyLi();
  126. //Re build
  127. $li = this.createLi();
  128. this.$newElement.find('ul').append( $li );
  129. //render view
  130. this.render();
  131. },
  132. destroyLi:function() {
  133. this.$newElement.find('li').remove();
  134. },
  135. createLi: function() {
  136. var _this = this;
  137. var _li = [];
  138. var _liA = [];
  139. var _liHtml = '';
  140. this.$element.find('option').each(function(){
  141. _li.push($(this).text());
  142. });
  143. this.$element.find('option').each(function(index) {
  144. //Get the class and text for the option
  145. var optionClass = $(this).attr("class") !== undefined ? $(this).attr("class") : '';
  146. var text = $(this).text();
  147. var subtext = $(this).data('subtext') !== undefined ? '<small class="muted">'+$(this).data('subtext')+'</small>' : '';
  148. //Append any subtext to the main text.
  149. text+=subtext;
  150. if ($(this).parent().is('optgroup') && $(this).data('divider') != true) {
  151. if ($(this).index() == 0) {
  152. //Get the opt group label
  153. var label = $(this).parent().attr('label');
  154. var labelSubtext = $(this).parent().data('subtext') !== undefined ? '<small class="muted">'+$(this).parent().data('subtext')+'</small>' : '';
  155. label += labelSubtext;
  156. if ($(this)[0].index != 0) {
  157. _liA.push(
  158. '<div class="divider"></div>'+
  159. '<dt>'+label+'</dt>'+
  160. _this.createA(text, "opt " + optionClass )
  161. );
  162. } else {
  163. _liA.push(
  164. '<dt>'+label+'</dt>'+
  165. _this.createA(text, "opt " + optionClass ));
  166. }
  167. } else {
  168. _liA.push( _this.createA(text, "opt " + optionClass ) );
  169. }
  170. } else if ($(this).data('divider') == true) {
  171. _liA.push('<div class="divider"></div>');
  172. } else if ($(this).data('hidden') == true) {
  173. _liA.push('');
  174. } else {
  175. _liA.push( _this.createA(text, optionClass ) );
  176. }
  177. });
  178. if (_li.length > 0) {
  179. for (var i = 0; i < _li.length; i++) {
  180. var $option = this.$element.find('option').eq(i);
  181. _liHtml += "<li rel=" + i + ">" + _liA[i] + "</li>";
  182. }
  183. }
  184. //If we dont have a selected item, and we dont have a title, select the first element so something is set in the button
  185. if(this.$element.find('option:selected').length==0 && !_this.options.title) {
  186. this.$element.find('option').eq(0).prop('selected', true).attr('selected', 'selected');
  187. }
  188. return $(_liHtml);
  189. },
  190. createA:function(test, classes) {
  191. return '<a tabindex="-1" href="#" class="'+classes+'">' +
  192. '<span class="pull-left">' + test + '</span>' +
  193. '</a>';
  194. },
  195. render:function() {
  196. var _this = this;
  197. //Set width of select
  198. if (this.options.width == 'auto') {
  199. var ulWidth = this.$newElement.find('.dropdown-menu').css('width');
  200. this.$newElement.css('width',ulWidth);
  201. } else if (this.options.width && this.options.width != 'auto') {
  202. this.$newElement.css('width',this.options.width);
  203. }
  204. //Update the LI to match the SELECT
  205. this.$element.find('option').each(function(index) {
  206. _this.setDisabled(index, $(this).is(':disabled') || $(this).parent().is(':disabled') );
  207. _this.setSelected(index, $(this).is(':selected') );
  208. });
  209. var selectedItems = this.$element.find('option:selected').map(function(index,value) {
  210. if($(this).attr('title')!=undefined) {
  211. return $(this).attr('title');
  212. } else {
  213. return $(this).text();
  214. }
  215. }).toArray();
  216. //Convert all the values into a comma delimited string
  217. var title = selectedItems.join(", ");
  218. //If this is multi select, and the selectText type is count, the show 1 of 2 selected etc..
  219. if(_this.multiple && _this.options.selectedTextFormat.indexOf('count') > -1) {
  220. var max = _this.options.selectedTextFormat.split(">");
  221. if( (max.length>1 && selectedItems.length > max[1]) || (max.length==1 && selectedItems.length>=2)) {
  222. title = selectedItems.length +' of ' + this.$element.find('option').length + ' selected';
  223. }
  224. }
  225. //If we dont have a title, then use the default, or if nothing is set at all, use the not selected text
  226. if(!title) {
  227. title = _this.options.title != undefined ? _this.options.title : _this.options.noneSelectedText;
  228. }
  229. this.$element.next('.select').find('.filter-option').html( title );
  230. },
  231. setSelected:function(index, selected) {
  232. if(selected) {
  233. this.$newElement.find('li').eq(index).addClass('selected');
  234. } else {
  235. this.$newElement.find('li').eq(index).removeClass('selected');
  236. }
  237. },
  238. setDisabled:function(index, disabled) {
  239. if(disabled) {
  240. this.$newElement.find('li').eq(index).addClass('disabled');
  241. } else {
  242. this.$newElement.find('li').eq(index).removeClass('disabled');
  243. }
  244. },
  245. checkDisabled: function() {
  246. if (this.$element.is(':disabled')) {
  247. this.button.addClass('disabled');
  248. this.button.click(function(e) {
  249. e.preventDefault();
  250. });
  251. }
  252. },
  253. checkTabIndex: function() {
  254. if (this.$element.is('[tabindex]')) {
  255. var tabindex = this.$element.attr("tabindex");
  256. this.button.attr('tabindex', tabindex);
  257. }
  258. },
  259. clickListener: function() {
  260. var _this = this;
  261. $('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
  262. this.$newElement.on('click', 'li a', function(e){
  263. var clickedIndex = $(this).parent().index(),
  264. $this = $(this).parent(),
  265. $select = $this.parents('.select');
  266. //Dont close on multi choice menu
  267. if(_this.multiple) {
  268. e.stopPropagation();
  269. }
  270. e.preventDefault();
  271. //Dont run if we have been disabled
  272. if ($select.prev('select').not(':disabled') && !$(this).parent().hasClass('disabled')){
  273. //Deselect all others if not multi select box
  274. if (!_this.multiple) {
  275. $select.prev('select').find('option').removeAttr('selected');
  276. $select.prev('select').find('option').eq(clickedIndex).prop('selected', true).attr('selected', 'selected');
  277. }
  278. //Else toggle the one we have chosen if we are multi selet.
  279. else {
  280. var selected = $select.prev('select').find('option').eq(clickedIndex).prop('selected');
  281. if(selected) {
  282. $select.prev('select').find('option').eq(clickedIndex).removeAttr('selected');
  283. } else {
  284. $select.prev('select').find('option').eq(clickedIndex).prop('selected', true).attr('selected', 'selected');
  285. }
  286. }
  287. $select.find('.filter-option').html($this.text());
  288. $select.find('button').focus();
  289. // Trigger select 'change'
  290. $select.prev('select').trigger('change');
  291. }
  292. });
  293. this.$newElement.on('click', 'li.disabled a, li dt, li .divider', function(e) {
  294. e.preventDefault();
  295. e.stopPropagation();
  296. $select = $(this).parent().parents('.select');
  297. $select.find('button').focus();
  298. });
  299. this.$element.on('change', function(e) {
  300. _this.render();
  301. });
  302. },
  303. val:function(value) {
  304. if(value!=undefined) {
  305. this.$element.val( value );
  306. this.$element.trigger('change');
  307. return this.$element;
  308. } else {
  309. return this.$element.val();
  310. }
  311. }
  312. };
  313. $.fn.selectpicker = function(option, event) {
  314. //get the args of the outer function..
  315. var args = arguments;
  316. var value;
  317. var chain = this.each(function () {
  318. var $this = $(this),
  319. data = $this.data('selectpicker'),
  320. options = typeof option == 'object' && option;
  321. if (!data) {
  322. $this.data('selectpicker', (data = new Selectpicker(this, options, event)));
  323. } else {
  324. for(var i in option) {
  325. data[i]=option[i];
  326. }
  327. }
  328. if (typeof option == 'string') {
  329. //Copy the value of option, as once we shift the arguments
  330. //it also shifts the value of option.
  331. property = option;
  332. if(data[property] instanceof Function) {
  333. [].shift.apply(args);
  334. value = data[property].apply(data, args);
  335. } else {
  336. value = data[property];
  337. }
  338. }
  339. });
  340. if(value!=undefined) {
  341. return value;
  342. } else {
  343. return chain;
  344. }
  345. };
  346. $.fn.selectpicker.defaults = {
  347. style: null,
  348. size: 'auto',
  349. title: null,
  350. selectedTextFormat : 'values',
  351. noneSelectedText : 'Nothing selected',
  352. width: null,
  353. menuStyle: null,
  354. toggleSize: null
  355. }
  356. }(window.jQuery);