├── .gitignore ├── .npmignore ├── .travis.yml ├── tsconfig.json ├── dist ├── bootstrap-4-autocomplete.d.ts ├── bootstrap-4-autocomplete.min.js └── bootstrap-4-autocomplete.js ├── gulpfile.js ├── package.json ├── LICENSE ├── CHANGELOG.md ├── example └── example.html ├── src └── bootstrap-4-autocomplete.ts └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src 2 | .gitignore 3 | .travis.yml 4 | gulpfile.js 5 | tsconfig.json 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | node_js: 4 | - node 5 | 6 | branches: 7 | only: 8 | - master 9 | 10 | before_script: 11 | - rm -r node_modules 12 | - rm package-lock.json 13 | - npm install 14 | 15 | script: 16 | - npm run build 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | "src/**/*.ts", 4 | ], 5 | "compilerOptions": { 6 | "target": "ES3", 7 | "module": "none", 8 | "moduleResolution": "node", 9 | "declaration": true, 10 | "outDir": "dist", 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /dist/bootstrap-4-autocomplete.d.ts: -------------------------------------------------------------------------------- 1 | interface AutocompleteItem { 2 | value: string; 3 | label: string; 4 | } 5 | interface AutocompleteOptions { 6 | dropdownOptions?: Bootstrap.DropdownOption; 7 | dropdownClass?: string | string[]; 8 | highlightClass?: string | string[]; 9 | highlightTyped?: boolean; 10 | label?: string; 11 | maximumItems?: number; 12 | onSelectItem?: (item: AutocompleteItem, element: HTMLElement) => void; 13 | source?: object; 14 | treshold?: number; 15 | value?: string; 16 | } 17 | interface JQuery { 18 | autocomplete(options: AutocompleteOptions): JQuery; 19 | } 20 | -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | const { src, dest, series } = require('gulp'); 2 | const del = require('del'); 3 | const rename = require('gulp-rename'); 4 | const typescript = require('gulp-typescript'); 5 | const uglify = require('gulp-uglify'); 6 | 7 | const target = 'dist'; 8 | 9 | var tsProject = typescript.createProject('tsconfig.json'); 10 | 11 | function clean() { 12 | return del([target]); 13 | } 14 | 15 | function compile() { 16 | const compiled = tsProject.src().pipe(tsProject()); 17 | compiled.dts.pipe(dest(target)); 18 | return compiled.js.pipe(dest(target)); 19 | } 20 | 21 | function min() { 22 | return src(target + '/bootstrap-4-autocomplete.js') 23 | .pipe(uglify()) 24 | .pipe(rename('bootstrap-4-autocomplete.min.js')) 25 | .pipe(dest(target)); 26 | } 27 | 28 | const build = series( 29 | clean, 30 | compile, 31 | min 32 | ); 33 | 34 | exports.default = build; 35 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bootstrap-4-autocomplete", 3 | "version": "1.3.2", 4 | "description": "A simple autocomplete/typeahead for Bootstrap 4 and jQuery", 5 | "main": "dist/bootstrap-4-autocomplete.js", 6 | "typings": "dist/bootstrap-4-autocomplete.d.ts", 7 | "scripts": { 8 | "build": "gulp", 9 | "test": "echo \"No test specified\"", 10 | "deliver": "np" 11 | }, 12 | "keywords": [ 13 | "bootstrap", 14 | "jquery", 15 | "autocomplete", 16 | "typeahead" 17 | ], 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/Honatas/bootstrap-4-autocomplete" 21 | }, 22 | "author": "Jonatas de Moraes Junior", 23 | "license": "MIT", 24 | "dependencies": { 25 | "bootstrap": "^4.5.3", 26 | "jquery": "^3.5.1" 27 | }, 28 | "devDependencies": { 29 | "@types/bootstrap": "^4.5.1", 30 | "@types/jquery": "^3.5.4", 31 | "del": "^5.1.0", 32 | "gulp": "^4.0.2", 33 | "gulp-rename": "^1.4.0", 34 | "gulp-typescript": "^5.0.1", 35 | "gulp-uglify": "^3.0.2", 36 | "typescript": "^4.0.5" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Honatas 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Change Log 2 | 3 | ### v1.3.2 (2021-01-28) 4 | - Added reference to jsfiddle on readme 5 | 6 | ### v1.3.0 (2020-11-06) 7 | - Added dropdownClass option to apply classes to the dropdown container 8 | - dropdownClass and highlightClass can now be passed a string or an array of strings 9 | - if maximumItems set to 0 or less, display all available items 10 | 11 | ### v1.2.3 (2020-04-28) 12 | - Fixed vulnerability (dependency) 13 | 14 | ### v1.2.2 (2020-01-09) 15 | - Add entry point (main) to package.json 16 | 17 | ### v1.2.1 (2020-01-07) 18 | - Fixed destroying previously set click and keyup events 19 | 20 | ### v1.2.0 (2019-09-15) 21 | - Added the input element as a parameter to onSelectItem 22 | - Fixed showing empty 23 | 24 | ### v1.1.0 (2019-09-14) 25 | - Added text highlighting 26 | - Fixed wrong positioning 27 | 28 | ### v1.0.4 (2019-09-13) 29 | - Fixed autocomplete appearing on click with more items than it should 30 | - Example added 31 | - Now building with Gulp 32 | 33 | ### v1.0.3 (2019-09-06) 34 | - Updated README with badges 35 | 36 | ### v1.0.2 (2019-09-04) 37 | - Fixed undesired behaviour when setting autocomplete on a same field multiple times 38 | - Fixed showing more items than desired 39 | - Fixed showing full search when backspacing to empty field 40 | 41 | ### v1.0.1 (2019-09-04) 42 | - Fixed multiple instances sources overlapping each other 43 | - Fixed bad positioning on focus 44 | -------------------------------------------------------------------------------- /dist/bootstrap-4-autocomplete.min.js: -------------------------------------------------------------------------------- 1 | !function(u){var n={treshold:4,maximumItems:5,highlightTyped:!0,highlightClass:"text-primary"};function p(e,t,o){var a;if(o.highlightTyped){var n=t.label.toLowerCase().indexOf(e.toLowerCase());a=t.label.substring(0,n)+''+t.label.substring(n,n+e.length)+""+t.label.substring(n+e.length,t.label.length)}else a=t.label;return'"}function l(e,t){var o=e.val();if(o.length=t.maximumItems))break}return e.next().find(".dropdown-item").click(function(){e.val(u(this).text()),t.onSelectItem&&t.onSelectItem({value:u(this).data("value"),label:u(this).text()},e[0])}),a.children().length}u.fn.autocomplete=function(e){var t={};u.extend(t,n,e);var o=u(this);o.parent().removeClass("dropdown"),o.removeAttr("data-toggle"),o.removeClass("dropdown-toggle"),o.parent().find(".dropdown-menu").remove(),o.dropdown("dispose"),o.parent().addClass("dropdown"),o.attr("data-toggle","dropdown"),o.addClass("dropdown-toggle");var a=u('');return t.dropdownClass&&a.addClass(t.dropdownClass),o.after(a),o.dropdown(t.dropdownOptions),this.off("click.autocomplete").click("click.autocomplete",function(e){0==l(o,t)&&(e.stopPropagation(),o.dropdown("hide"))}),this.off("keyup.autocomplete").keyup("keyup.autocomplete",function(){0 2 | 3 | 4 | 5 | 6 | 7 | 8 | Bootstrap 4 Autocomple Example 9 | 10 | 11 |
12 |
13 | 14 | 15 |
16 |
17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /dist/bootstrap-4-autocomplete.js: -------------------------------------------------------------------------------- 1 | (function ($) { 2 | var defaults = { 3 | treshold: 4, 4 | maximumItems: 5, 5 | highlightTyped: true, 6 | highlightClass: 'text-primary' 7 | }; 8 | function createItem(lookup, item, opts) { 9 | var label; 10 | if (opts.highlightTyped) { 11 | var idx = item.label.toLowerCase().indexOf(lookup.toLowerCase()); 12 | label = item.label.substring(0, idx) 13 | + '' + item.label.substring(idx, idx + lookup.length) + '' 14 | + item.label.substring(idx + lookup.length, item.label.length); 15 | } 16 | else { 17 | label = item.label; 18 | } 19 | return ''; 20 | } 21 | function expandClassArray(classes) { 22 | if (typeof classes == "string") { 23 | return classes; 24 | } 25 | if (classes.length == 0) { 26 | return ''; 27 | } 28 | var ret = ''; 29 | for (var _i = 0, classes_1 = classes; _i < classes_1.length; _i++) { 30 | var clas = classes_1[_i]; 31 | ret += clas + ' '; 32 | } 33 | return ret.substring(0, ret.length - 1); 34 | } 35 | function createItems(field, opts) { 36 | var lookup = field.val(); 37 | if (lookup.length < opts.treshold) { 38 | field.dropdown('hide'); 39 | return 0; 40 | } 41 | var items = field.next(); 42 | items.html(''); 43 | var count = 0; 44 | var keys = Object.keys(opts.source); 45 | for (var i = 0; i < keys.length; i++) { 46 | var key = keys[i]; 47 | var object = opts.source[key]; 48 | var item = { 49 | label: opts.label ? object[opts.label] : key, 50 | value: opts.value ? object[opts.value] : object 51 | }; 52 | if (item.label.toLowerCase().indexOf(lookup.toLowerCase()) >= 0) { 53 | items.append(createItem(lookup, item, opts)); 54 | if (opts.maximumItems > 0 && ++count >= opts.maximumItems) { 55 | break; 56 | } 57 | } 58 | } 59 | // option action 60 | field.next().find('.dropdown-item').click(function () { 61 | field.val($(this).text()); 62 | if (opts.onSelectItem) { 63 | opts.onSelectItem({ 64 | value: $(this).data('value'), 65 | label: $(this).text() 66 | }, field[0]); 67 | } 68 | }); 69 | return items.children().length; 70 | } 71 | $.fn.autocomplete = function (options) { 72 | // merge options with default 73 | var opts = {}; 74 | $.extend(opts, defaults, options); 75 | var _field = $(this); 76 | // clear previously set autocomplete 77 | _field.parent().removeClass('dropdown'); 78 | _field.removeAttr('data-toggle'); 79 | _field.removeClass('dropdown-toggle'); 80 | _field.parent().find('.dropdown-menu').remove(); 81 | _field.dropdown('dispose'); 82 | // attach dropdown 83 | _field.parent().addClass('dropdown'); 84 | _field.attr('data-toggle', 'dropdown'); 85 | _field.addClass('dropdown-toggle'); 86 | var dropdown = $(''); 87 | // attach dropdown class 88 | if (opts.dropdownClass) 89 | dropdown.addClass(opts.dropdownClass); 90 | _field.after(dropdown); 91 | _field.dropdown(opts.dropdownOptions); 92 | this.off('click.autocomplete').click('click.autocomplete', function (e) { 93 | if (createItems(_field, opts) == 0) { 94 | // prevent show empty 95 | e.stopPropagation(); 96 | _field.dropdown('hide'); 97 | } 98 | ; 99 | }); 100 | // show options 101 | this.off('keyup.autocomplete').keyup('keyup.autocomplete', function () { 102 | if (createItems(_field, opts) > 0) { 103 | _field.dropdown('show'); 104 | } 105 | else { 106 | // sets up positioning 107 | _field.click(); 108 | } 109 | }); 110 | return this; 111 | }; 112 | }(jQuery)); 113 | -------------------------------------------------------------------------------- /src/bootstrap-4-autocomplete.ts: -------------------------------------------------------------------------------- 1 | interface AutocompleteItem { 2 | value: string, 3 | label: string, 4 | } 5 | 6 | interface AutocompleteOptions { 7 | dropdownOptions?: Bootstrap.DropdownOption, 8 | dropdownClass?: string | string[], 9 | highlightClass?: string | string[], 10 | highlightTyped?: boolean, 11 | label?: string, 12 | maximumItems?: number, 13 | onSelectItem?: (item: AutocompleteItem, element: HTMLElement) => void, 14 | source?: object, 15 | treshold?: number, 16 | value?: string, 17 | } 18 | 19 | interface JQuery { 20 | autocomplete(options: AutocompleteOptions): JQuery; 21 | } 22 | 23 | (function ( $ ) { 24 | 25 | let defaults: AutocompleteOptions = { 26 | treshold: 4, 27 | maximumItems: 5, 28 | highlightTyped: true, 29 | highlightClass: 'text-primary', 30 | }; 31 | 32 | function createItem(lookup: string, item: AutocompleteItem, opts: AutocompleteOptions):string { 33 | let label: string; 34 | if (opts.highlightTyped) { 35 | const idx = item.label.toLowerCase().indexOf(lookup.toLowerCase()); 36 | label = item.label.substring(0, idx) 37 | + '' + item.label.substring(idx, idx + lookup.length) + '' 38 | + item.label.substring(idx + lookup.length, item.label.length); 39 | } else { 40 | label = item.label; 41 | } 42 | return ''; 43 | } 44 | 45 | function expandClassArray(classes: string | string[]): string { 46 | if (typeof classes == "string") { 47 | return classes; 48 | } 49 | if (classes.length == 0) { 50 | return ''; 51 | } 52 | let ret = ''; 53 | for (const clas of classes) { 54 | ret += clas + ' '; 55 | } 56 | return ret.substring(0, ret.length - 1); 57 | } 58 | 59 | function createItems(field: JQuery, opts: AutocompleteOptions) { 60 | const lookup = field.val() as string; 61 | if (lookup.length < opts.treshold) { 62 | field.dropdown('hide'); 63 | return 0; 64 | } 65 | 66 | const items = field.next(); 67 | items.html(''); 68 | 69 | let count = 0; 70 | const keys = Object.keys(opts.source); 71 | for (let i = 0; i < keys.length; i++) { 72 | const key = keys[i]; 73 | const object = opts.source[key]; 74 | const item = { 75 | label: opts.label ? object[opts.label] : key, 76 | value: opts.value ? object[opts.value]: object, 77 | }; 78 | if (item.label.toLowerCase().indexOf(lookup.toLowerCase()) >= 0) { 79 | items.append(createItem(lookup, item, opts)); 80 | if (opts.maximumItems > 0 && ++count >= opts.maximumItems) { 81 | break; 82 | } 83 | } 84 | } 85 | 86 | // option action 87 | field.next().find('.dropdown-item').click(function() { 88 | field.val($(this).text()); 89 | if (opts.onSelectItem) { 90 | opts.onSelectItem({ 91 | value: $(this).data('value'), 92 | label: $(this).text(), 93 | }, field[0]); 94 | } 95 | }); 96 | 97 | return items.children().length; 98 | } 99 | 100 | $.fn.autocomplete = function(options) { 101 | // merge options with default 102 | let opts: AutocompleteOptions = {}; 103 | $.extend(opts, defaults, options); 104 | 105 | let _field = $(this); 106 | 107 | // clear previously set autocomplete 108 | _field.parent().removeClass('dropdown'); 109 | _field.removeAttr('data-toggle'); 110 | _field.removeClass('dropdown-toggle'); 111 | _field.parent().find('.dropdown-menu').remove(); 112 | _field.dropdown('dispose'); 113 | 114 | // attach dropdown 115 | _field.parent().addClass('dropdown'); 116 | _field.attr('data-toggle', 'dropdown'); 117 | _field.addClass('dropdown-toggle'); 118 | const dropdown = $(''); 119 | // attach dropdown class 120 | if (opts.dropdownClass) dropdown.addClass(opts.dropdownClass); 121 | _field.after(dropdown); 122 | 123 | _field.dropdown(opts.dropdownOptions); 124 | 125 | this.off('click.autocomplete').click('click.autocomplete', function(e) { 126 | if (createItems(_field, opts) == 0) { 127 | // prevent show empty 128 | e.stopPropagation(); 129 | _field.dropdown('hide'); 130 | }; 131 | }); 132 | 133 | // show options 134 | this.off('keyup.autocomplete').keyup('keyup.autocomplete', function() { 135 | if (createItems(_field, opts) > 0) { 136 | _field.dropdown('show'); 137 | } else { 138 | // sets up positioning 139 | _field.click(); 140 | } 141 | }); 142 | 143 | return this; 144 | }; 145 | }( jQuery )); 146 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bootstrap 4 Autocomplete 2 | 3 | [![Travis](https://img.shields.io/travis/honatas/bootstrap-4-autocomplete?style=plastic)](https://travis-ci.org/Honatas/bootstrap-4-autocomplete "View the build on Travis") 4 | [![David](https://img.shields.io/david/honatas/bootstrap-4-autocomplete?style=plastic)](https://david-dm.org/honatas/bootstrap-4-autocomplete "View the dependencies status on David") 5 | [![GitHub](https://img.shields.io/github/license/honatas/bootstrap-4-autocomplete?style=plastic)](https://github.com/Honatas/bootstrap-4-autocomplete "View this project on GitHub") 6 | [![npm](https://img.shields.io/npm/v/bootstrap-4-autocomplete?style=plastic)](https://npmjs.org/package/bootstrap-4-autocomplete "View this project on npm") 7 | [![typescript](https://img.shields.io/badge/made%20with-Typescript-blue?style=plastic)](https://www.typescriptlang.org/ "Try Typescript") 8 | [![coffee](https://img.shields.io/badge/buy%20me%20a-coffee-brown?style=plastic)](https://ko-fi.com/honatas "Buy me a coffee") 9 | 10 | A very small (less than 2Kb) autocomplete/typeahead for Bootstrap 4 and jQuery. 11 | 12 | It uses the default [Dropdown](https://getbootstrap.com/docs/4.3/components/dropdowns/) component from Bootstrap 4 to create the list of autocomplete items. 13 | 14 | 15 | 16 | ## Install 17 | 18 | You can get it from npm: 19 | 20 | npm install bootstrap-4-autocomplete 21 | 22 | Or you can get it from a CDN. Just be careful to add it to your HTML **AFTER** Jquery, Popperjs and Bootstrap: 23 | 24 | ```html 25 | 26 | 27 | 28 | 29 | 30 | 31 | ``` 32 | 33 | 34 | 35 | ## Typescript 36 | 37 | If your project uses Typescript, Bootstrap 4 Autocomplete has type definitions. If for some reason your IDE/Compiler can't find the definitions automatically, you can add them manually on your tsconfig.json file in the "includes" section: 38 | 39 | includes: ["node_modules/bootstrap-4-autocomplete/dist/bootstrap-4-autocomplete.d.ts"] 40 | 41 | 42 | 43 | ## Usage 44 | 45 | Take a look at this [fiddle](https://jsfiddle.net/Honatas/n943qob1/5/) to get an overview of a simple usage. 46 | 47 | Given you have a textfield with id "myAutocomplete", you can: 48 | 49 | ```javascript 50 | $("#myAutocomplete").autocomplete(options); 51 | ``` 52 | 53 | Options is a JSON object with the following attributes (in alphabetical order): 54 | 55 | **dropdownOptions**: 56 | It's the same options from Bootstrap's Dropdown, documented [here](https://getbootstrap.com/docs/4.3/components/dropdowns/#options). 57 | 58 | **dropdownClass**: 59 | The class of the dropdown-menu element, which is the box that is displayed. Can take a string or an array of strings. 60 | 61 | **highlightClass**: 62 | The class to use when highlighting typed text on items. Only used when highlightTyped is true. Default is text-primary. Can take a string or an array of strings. 63 | 64 | **highlightTyped**: 65 | Wether to highlight (style) typed text on items. Default is true. 66 | 67 | **label**: 68 | Where to find the label on your source. The label is what will be shown on each item in the autocomplete list. 69 | 70 | **maximumItems**: 71 | How many items you want to show when the autocomplete is displayed. Default is 5. Set to 0 to display all available items. 72 | 73 | **onSelectItem**: 74 | A callback that is fired every time an item is selected. It receives two parameters: the first is the selected item, the second is the textfield element. The selected item has the format: 75 | 76 | { value: value, label: label } 77 | 78 | Note that you don't have to use this callback to set the text in the textfield, this is done automatically. 79 | 80 | **source**: 81 | The data from where autocomplete will lookup items to show. This data has to be a JSON object. The default format for this object is: 82 | 83 | { "label1": 1, "label2": 2, ...} 84 | 85 | If your JSON has this format, you don't need to set the label and value options, as they will be retrieved automatically. Otherwise, you can pass any format as you want, given you set the value and label options. 86 | 87 | **treshold**: 88 | The number of characters that need to be typed on the input in order to trigger the autocomplete. Default is 4. 89 | 90 | **value**: 91 | Where to find the value on your source. 92 | 93 | 94 | 95 | ## How it works 96 | 97 | When you call autocomplete on a texfield (also known as input type="text"), this lib builds a Dropdown around the textfield, having it's parent as the container. The textfield is then injected an **onkeyup** event that triggers the Dropdown when the length of the text typed is equal to or greater than the treshold. When this happens, the data is then filtered to get only the items that contain the text typed. When you activate one of the items, the textfield's value is set to that item's label. 98 | 99 | 100 | 101 | ## Contributions 102 | 103 | Feel free to open an issue or add a pull request. Anytime. Really, I mean it. 104 | 105 | Also, if you like my work, I'll let you know that I love [coffee](https://ko-fi.com/honatas). \*wink wink nudge nudge\* 106 | --------------------------------------------------------------------------------