AJAX Autocomplete Plugin For Bootstrap Select

AJAX Autocomplete Plugin For Bootstrap Select
File Size: 1.16 MB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

Ajax Bootstrap Select is a jQuery extension for the popular Bootstrap select plugin that enables the AJAX autocomplete (live search) functionality on the dropdown select.

The plugin fetches JSON data from a remote data source and dynamically populates the select options via AJAX requests.

How to use it:

1. Include the necessary jQuery library, Bootstrap framework and Bootstrap select plugin on the page.

<!-- Stylesheet -->
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.min.css">

<!-- JavaScript -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>

2. Include the Ajax Bootstrap Select's JavaScript and Stylesheet on the page.

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

3. Call the chained functions (Bootstrap Select & Ajax Bootstrap Select) on the select element and specify the remote data you want to fetch as these:

<select id="ajax-select" class="selectpicker" data-live-search="true"></select>
$('.selectpicker').selectpicker().ajaxSelectPicker({

  ajax: {

    // data source
    url: 'dataset.json', 

    // ajax type
    type: 'POST',

    // data type
    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}}}'
    }
  },

  // function to preprocess JSON data
  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;
  }

});

4. All default configuration options.

/**
* @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>'
}

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