jQuery Plugin For Filterable Bootstrap Dropdown Select - Bootstrap Select

jQuery Plugin For Filterable Bootstrap Dropdown Select - Bootstrap Select
File Size: 260 KB
Views Total: 63248
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

Bootstrap Select is a jQuery plugin to enhance the default Bootstrap dropdown select with multiple options like: optgoup support, auto-completion, clear selection and live filtering.

Dependencies:

Installation:

# Yarn
$ yarn add bootstrap-select

# NPM
$ npm install bootstrap-select --save

How to use it:

1. Include the jQuery Bootstrap Select plugin and other required resources into your Bootstrap page.

<!-- Bootstrap 4 Stylesheet -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

<!-- Bootstrap Select Stylesheet -->
<link href="/path/to/bootstrap-select.min.css" rel="stylesheet">

<!-- Bootstrap 4 JavaScript -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>

<!-- Bootstrap Select Main JavaScript -->
<script src="/path/to/bootstrap-select.min.js"></script>

<!-- Bootstrap Select Language JavaScript -->
<script src="/path/to/i18n/defaults-LANGUAGE.min.js"></script>

2. Just add the class 'selectpicker' to your select element and done.

<select class="selectpicker">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>

3. You can also initialize the plugin by call the function on the 'select' element.

$('select').selectpicker();

4. All default plugin settings.

$('select').selectpicker({

  // text for none selected
  noneSelectedText: 'Nothing selected',

  // text for no results
  noneResultsText: 'No results matched {0}',
  countSelectedText: function (numSelected, numTotal) {
    return (numSelected == 1) ? "{0} item selected" : "{0} items selected";
  },

  // text for max options
  maxOptionsText: function (numAll, numGroup) {
    return [
      (numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)',
      (numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)'
    ];
  },

  // text for select all
  selectAllText: 'Select All',

  // text for deselect all
  deselectAllText: 'Deselect All',

  // enables done button
  doneButton: false,

  // text for done button
  doneButtonText: 'Close',

  // custom separator
  multipleSeparator: ', ',

  // basic class
  styleBase: 'btn',

  // button classes
  style: classNames.BUTTONCLASS,

  // 'auto' | integer | false
  size: 'auto',

  // title for dropdown select
  title: null,

  // values' | 'static' | 'count' | 'count > x'
  selectedTextFormat: 'values',

  // width
  width: false,

  // string | false
  container: false,

  // hides disabled options
  hideDisabled: false,

  // shows sub text
  showSubtext: false,

  // shows icons
  showIcon: true,

  // shows content
  showContent: true,

  // auto reposition to fit screen
  dropupAuto: true,

  // adds a header to the dropdown select
  header: false,

  // live filter options
  liveSearch: false,
  liveSearchPlaceholder: null,
  liveSearchNormalize: false,
  liveSearchStyle: 'contains',

  // shows Select All & Deselect All
  actionsBox: false,

  // icon base
  iconBase: 'glyphicon',

  // tick icon
  tickIcon: 'glyphicon-ok',

  // shows tick
  showTick: false,

  // custom template
  template: {
    caret: '<span class="caret"></span>'
  },

  // integer | false
  maxOptions: false,

  // enables the device's native select for the dropdown select
  mobile: false,

  // if true, treats the tab character like the enter or space characters within the selectpicker dropdown.
  selectOnTab: false,

  // boolean | 'auto'
  dropdownAlignRight: false,

  // padding
  windowPadding: 0,

  // If enabled, the items in the dropdown will be rendered using virtualization (i.e. only the items that are within the viewport will be rendered). 
  // This drastically improves performance for selects with a large number of options. 
  // Set to an integer to only use virtualization if the select has at least that number of options.
  virtualScroll: 600
  
});

5. API methods.

// Sets the selected value
$('.selectpicker').selectpicker('val', 'Mustard');
$('.selectpicker').selectpicker('val', ['Mustard','Relish']);

// Selects all items
$('.selectpicker').selectpicker('selectAll');

// Deselects all items
$('.selectpicker').selectpicker('deselectAll');

// Re-renders the plugin
$('.selectpicker').selectpicker('render')

$('.selectpicker').selectpicker('render');

// Enables mobile scrolling
$('.selectpicker').selectpicker('mobile')

// Modifies the class(es)
$('.selectpicker').selectpicker('setStyle')
// Replace Class
$('.selectpicker').selectpicker('setStyle', 'btn-danger');
// Add Class
$('.selectpicker').selectpicker('setStyle', 'btn-large', 'add');
// Remove Class
$('.selectpicker').selectpicker('setStyle', 'btn-large', 'remove');

// Programmatically updates a select
$('.selectpicker').selectpicker('refresh')

// Programmatically toggles the select
$('.selectpicker').selectpicker('toggle')

// Hides the select
$('.selectpicker').selectpicker('hide')

// Shows the select
$('.selectpicker').selectpicker('show')

// Destroy the select
$('.selectpicker').selectpicker('destroy')

6. Event handlers available.

$('.selectpicker').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
  // do something...
});

$('.selectpicker').on('show.bs.select', function (relatedTarget) {
  // do something...
});

$('.selectpicker').on('shown.bs.select', function (relatedTarget) {
  // do something...
});

$('.selectpicker').on('hide.bs.select', function (relatedTarget) {
  // do something...
});

$('.selectpicker').on('hidden.bs.select', function (relatedTarget) {
  // do something...
});

$('.selectpicker').on('loaded.bs.select', function () {
  // do something...
});

$('.selectpicker').on('rendered.bs.select', function () {
  // do something...
});

$('.selectpicker').on('refreshed.bs.select', function () {
  // do something...
});

7. To use a remote data source you need load the Ajax-Bootstrap-Select extension in the document.

<link rel="stylesheet" href="/dist/css/ajax-bootstrap-select.css"/>
<script src="/dist/js/ajax-bootstrap-select.js"></script>

8. Add the data-live-search attribute to the select element.

<select id="selectpicker" class="selectpicker" data-live-search="true">
  ...
</select>

9. The example JavaScript to fetch options from a remote data source using AJAX.

var options = {
      ajax          : {
        url     : '/ajax',
        type    : 'POST',
        dataType: 'json',
        // Use "{{{q}}}" as a placeholder and Ajax Bootstrap Select will
        // automatically replace it with the value of the search query.
        data    : {
          q: '{{{q}}}'
        }
      },
      locale        : {
        emptyTitle: 'Select and Begin Typing'
      },
      log           : 3,
      preprocessData: function (data) {
        var i, l = data.length, array = [];
        if (l) {
          for (i = 0; i < l; i++) {
            array.push($.extend(true, data[i], {
              text : data[i].Name,
              value: data[i].Email,
              data : {
                subtext: data[i].Email
              }
            }));
          }
        }
        // You must always return a valid array when processing data. The
        // data argument passed is a clone and cannot be modified directly.
        return array;
      }
  };
  
$('.selectpicker').selectpicker().filter('.with-ajax').ajaxSelectPicker(options);

10. All possible options to customize the Ajax-Bootstrap-Select extension.

/**
* @member $.fn.ajaxSelectPicker.defaults
* @deprecated Since version `1.2.0`, see: {@link $.fn.ajaxSelectPicker.defaults#preprocessData}.
* @cfg {Function} ajaxResultsPreHook
*/

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Object} ajax (required)
* @markdown
* The options to pass to the jQuery AJAX request.
*
* ```js
* {
*     url: null, // Required.
*     type: 'POST',
*     dataType: 'json',
*     data: {
*         q: '{{{q}}}'
*     }
* }
* ```
*/
ajax: {
  url: null,
  type: 'POST',
  dataType: 'json',
  data: {
      q: '{{{q}}}'
  }
},

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Number} minLength = 0
* @markdown
* Invoke a request for empty search values.
*/
minLength: 0,

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {String} ajaxSearchUrl
* @deprecated Since version `1.2.0`, see: {@link $.fn.ajaxSelectPicker.defaults#ajax}.
*/

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {String} bindEvent = "keyup"
* @markdown
* The event to bind on the search input element to fire a request.
*/
bindEvent: 'keyup',

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Boolean} cache = true
* @markdown
* Cache previous requests. If enabled, the "enter" key (13) is enabled to
* allow users to force a refresh of the request.
*/
cache: true,

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Boolean} clearOnEmpty = true
* @markdown
* Clears the previous results when the search input has no value.
*/
clearOnEmpty: true,

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Boolean} clearOnError = true
* @markdown
* Clears the select list when the request returned with an error.
*/
clearOnError: true,

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Boolean} debug
* @deprecated Since version `1.2.0`, see: {@link $.fn.ajaxSelectPicker.defaults#log}.
*/

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Boolean} emptyRequest = false
* @markdown
* Invoke a request for empty search values.
*/
emptyRequest: false,

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Object} ignoredKeys
* @markdown
* Key codes to ignore so a request is not invoked with bindEvent. The
* "enter" key (13) will always be dynamically added to any list provided
* unless the "cache" option above is set to "true".
*
* ```js
* {
*     9: "tab",
*     16: "shift",
*     17: "ctrl",
*     18: "alt",
*     27: "esc",
*     37: "left",
*     39: "right",
*     38: "up",
*     40: "down",
*     91: "meta"
* }
* ```
*/
ignoredKeys: {
  9: "tab",
  16: "shift",
  17: "ctrl",
  18: "alt",
  27: "esc",
  37: "left",
  39: "right",
  38: "up",
  40: "down",
  91: "meta"
},

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {String} langCode = null
* @markdown
* The language code to use for string translation. By default this value
* is determined by the browser, however it is not entirely reliable. If
* you encounter inconsistencies, you may need to manually set this option.
*/
langCode: null,

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Object} locale = null
* @markdown
* Provide specific overrides for {@link $.fn.ajaxSelectPicker.locale locale string} translations. Values
* set here will cause the plugin to completely ignore defined locale string
* translations provided by the set language code. This is useful when
* needing to change a single value or when being used in a system that
* provides its own translations, like a CMS.
*
* ```js
* locale: {
*     searchPlaceholder: Drupal.t('Find...')
* }
* ```
*/
locale: null,

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {String|Number|Number} log = 'error'
* @markdown
* Determines the amount of logging that is displayed:
*
* - __0, false:__ Display no information from the plugin.
* - __1, 'error':__ Fatal errors that prevent the plugin from working.
* - __2, 'warn':__ Warnings that may impact the display of request data, but does not prevent the plugin from functioning.
* - __3, 'info':__ Provides additional information, generally regarding the from request data and callbacks.
* - __4, true, 'debug':__ Display all possible information. This will likely be highly verbose and is only recommended for development purposes or tracing an error with a request.
*/
log: 'error',

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Boolean} mixWithCurrents
* @deprecated Since version `1.2.0`, see: {@link $.fn.ajaxSelectPicker.defaults#preserveSelected}.
*/

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg placeHolderOption
* @deprecated Since version `1.2.0`, see: {@link $.fn.ajaxSelectPicker.locale#emptyTitle}.
*/

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Function|null} preprocessData = function(){}
* @markdown
* Process the raw data returned from a request.
*
* The following arguments are passed to this callback:
*
* - __data__ - `Array` The raw data returned from the request, passed by reference.
*
* This callback must return one of the following:
*
* - `Array` - A new array of items. This will replace the passed data.
* - `undefined|null|false` - Stops the callback and will use whatever modifications have been made to data.
*
* ```js
* function (data) {
*     var new = [], old = [], other = [];
*     for (var i = 0; i < data.length; i++) {
*         // Add items flagged as "new" to the correct array.
*         if (data[i].new) {
*             new.push(data[i]);
*         }
*         // Add items flagged as "old" to the correct array.
*         else if (data[i].old) {
*             old.push(data[i]);
*         }
*         // Something out of the ordinary happened, put these last.
*         else {
*             other.push(data[i]);
*         }
*     }
*     // Sort the data according to the order of these arrays.
*     return [].concat(new, old, other).
* }
* ```
*/
preprocessData: function () { },

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Boolean} preserveSelected = true
* @markdown
* Preserve selected items(s) between requests. When enabled, they will be
* placed in an `<optgroup>` with the label `Currently Selected`. Disable
* this option if you send your currently selected items along with your
* request and let the server handle this responsibility.
*/
preserveSelected: true,

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {String} preserveSelectedPosition = 'after'
* @markdown
* Place the currently selected options `'before'` or `'after'` the options
* returned from the request.
*/
preserveSelectedPosition: 'after',

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Function|null} processData = function(){}
* @markdown
* Process the data returned after this plugin, but before the list is built.
*/
processData: function () { },

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Number} requestDelay = 300
* @markdown
* The amount of time, in milliseconds, that must pass before a request
* is initiated. Each time the {@link $.fn.ajaxSelectPicker.defaults#bindEvent bindEvent} is fired, it will cancel the
* current delayed request and start a new one.
*/
requestDelay: 300,

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Boolean} restoreOnError = false
* @markdown
* Restores the select list with the previous results when the request
* returns with an error.
*/
restoreOnError: false,

/**
* @member $.fn.ajaxSelectPicker.defaults
* @cfg {Object} templates
* @markdown
* The DOM templates used in this plugin.
*
* ```js
* templates: {
*     // The placeholder for status updates pertaining to the list and request.
*     status: '<div class="status"></div>',
* }
* ```
*/
templates: {
  status: '<div class="status"></div>'
}

Changelog:

v1.13.18 (2020-06-27)

  • Bugs fixed

v1.13.17 (2020-05-08)

  • Bugs fixed

v1.13.16 (2020-04-25)

  • Bugs fixed

v1.13.15 (2020-04-21)

  • Bugs fixed

v1.13.14 (2020-04-18)

  • Fixed: TypeError: Cannot read property 'content' of undefined
  • Fixed: If a select has the title attribute set (and is not a multiple select), selecting an option doesn't update the value in the button
  • Improve CZ translations
  • Improve JP translations
  • Add Serbian translations
  • Add Thai translations

v1.13.13 (2020-04-17)

  • Fixed: data-size="false" not working
  • Fixed: calling deselectAll/selectAll immediately after page load throws error
  • Fixed: Dropup becomes a dropdown upon search
  • Fixed: Keyboard control over Bootstrap Dropdown components stops working
  • Fixed: Class bs-placeholder is no longer set on "default" values in 1.13.10

v1.13.12 (2019-10-11)

  • Fixed bugs.
  • Changed liveSearch input type from "text" to "search"

v1.13.11 (2019-09-20)

  • Fixed: Selecting non-existent option throws error in v1.13.10
  • Fixed: Desired width of dropdown menu breaks after resizing window
  • Fixed: bootstrap-select throws javascript error with jquery slim
  • Fixed: Multiple ticks in optgroup with data-max-options defined as "1"
  • Fixed: In IE11, options aren't visible when moving to bottom via "up" arrow key if select has an optgroup

v1.13.10 (2019-04-20)

  • Fixed: Keyboard navigation not working when searching and virtualScroll is false
  • Fixed: elements with .form-control class don't adjust height properly since Bootstrap 4.1.3
  • Fixed: showTick option not working as expected
  • Fixed: Screen reader doesn't read elements in expanded list (NVDA and JAWS)
  • Fixed: A standard select with a selected option doesn't scroll to the selected option if inside an optgroup
  • Fixed: hideDisabled and selectedTextFormat: count not working correctly if disabled options are selected
  • Fixed: selected option styling is not updated if .selectpicker('val', x) is called while dropdown menu is open
  • Fixed: menu size doesn't update when virtualScroll is disabled while the menu is open

v1.13.9 (2019-03-30)

  • Fixed: selected class is not removed properly when virtualScroll is disabled and choosing options at the bottom of the select
  • Fixed: setting BootstrapVersion option still shows console warning
  • Fixed: setting show-tick class doesn't work
  • Fixed: Every 'refresh' appends a new span.check-mark
  • Fixed: server-side error: HTMLSelectElement is not defined
  • Fixed: position bootstrap-select behind input field
  • Fixed: Mobile native menu not accessible
  • Fixed: JS errors are thrown when using bootstrap select on js-generated select (after calling destroy())
  • Fixed: Setting styleBase and empty style result in exception
  • Fixed: val() method fires changed.bs.select, but the select's previousValue is not passed through
  • Fixed: some default Bootstrap 4 styles are not being set when using BootstrapVersion
  • Fixed: width: fit in IE collapses button with text overflowing

v1.13.8 (2019-03-16)

  • Fixed: Does not work with form-inline from bootstrap
  • Fixed: The height of menu is calculated incorrectly with extra css
  • Fixed: Sanitizer error on large single selects without virtualScroll and one option selected

v1.13.7 (2019-03-13)

  • Fixed: val() method incorrectly fires a native change event
  • Fixed: The height of the select doesn't auto-size with multi-line options
  • Fixed: button height wrong if using an older doctype
  • Fixed: js folder missing in bower_components/bootstrap-select/dist
  • Fixed: style option can no longer include multiple styles
  • Fixed: auto width (data-width="auto") not working
  • Fixed: Selecting option by typing is not working correctly

v1.13.6 (2019-03-10)

  • Bugfixes

v1.13.5 (2018-12-12)

  • Bugfixes

v1.13.4 (2018-12-12)

  • Bugfixes
  • Improve/expand liveSearchNormalize
  • Replace JSHint with ESLint (clean up code)
  • Amharic locale
  • Latvian locale

v1.13.3 (2018-10-26)

  • Bugfixes
  • use sizeInfo.totalMenuWidth when determining dropdownAlignRight 'auto'
  • namespace window event listeners and remove when destroy is called

v1.13.2 (2018-09-16)

  • Add option to manually specify Bootstrap's version
  • Add support for Bootstrap dropdown's display property added in v4.1.0
  • Add check for $.fn.dropdown.Constructor
  • Improve readability of templates in createDropdown
  • Don't focus button if mobile option is set. use sibling selector to add focus style to button when select is focused. 

v1.13.1 (2018-08-25)

  • Fixed: HTML content in the subtext get escaped in 1.13.0
  • Fixed: Error retrieving Bootstrap version
  • Fixed: Bower description is too long
  • Fixed: noneSelectedText not working
  • Use innerHTML to set optgroup label
  • Don't change option selected status via changeAll if the option is disabled
  • Add option to manually specify Bootstrap's version
  • fix dividers in Bootstrap 4
  • use first option's class when calculating liHeight

v1.13.0 (2018-04-19)

  • Bugfixes
  • changed.bs.select now passes through previousValue as the third parameter (instead of the previous value of the option, which was redundant). This is the value of the select prior to being changed.
  • Supports Bootstrap 4 framework.

2018-04-14

  • allow searching of options with data-content

2018-03-13

  • fix data-width="fit"

2018-03-09

  • Show the selected option when 1 option is selected and selectedTextFormat is count.

2018-03-07

  • v2.2.5: Trim whitespace around selected options

2018-01-11

  • v2.2.5

2017-02-21

  • JS update

2015-11-28

  • Plugin initialisation optimised

2015-11-24

  • more configurations.

 


This awesome jQuery plugin is developed by snapappointments. For more Advanced Usages, please check the demo page or visit the official website.