GithubHelp home page GithubHelp logo

honatas / bootstrap-4-autocomplete Goto Github PK

View Code? Open in Web Editor NEW
56.0 2.0 31.0 159 KB

A simple autocomplete/typeahead for Bootstrap 4 and jQuery

License: MIT License

TypeScript 62.08% HTML 27.84% JavaScript 10.08%
autocomplete typeahead bootstrap jquery typescript javascript

bootstrap-4-autocomplete's Introduction

Bootstrap 4 Autocomplete

Travis David GitHub npm typescript coffee

A very small (less than 2Kb) autocomplete/typeahead for Bootstrap 4 and jQuery.

It uses the default Dropdown component from Bootstrap 4 to create the list of autocomplete items.

Install

You can get it from npm:

npm install bootstrap-4-autocomplete

Or you can get it from a CDN. Just be careful to add it to your HTML AFTER Jquery, Popperjs and Bootstrap:

<!-- Dependencies -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
<!-- Bootstrap 4 Autocomplete -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-4-autocomplete/dist/bootstrap-4-autocomplete.min.js" crossorigin="anonymous"></script>

Typescript

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:

includes: ["node_modules/bootstrap-4-autocomplete/dist/bootstrap-4-autocomplete.d.ts"]

Usage

Take a look at this fiddle to get an overview of a simple usage.

Given you have a textfield with id "myAutocomplete", you can:

$("#myAutocomplete").autocomplete(options);

Options is a JSON object with the following attributes (in alphabetical order):

dropdownOptions:
It's the same options from Bootstrap's Dropdown, documented here.

dropdownClass:
The class of the dropdown-menu element, which is the box that is displayed. Can take a string or an array of strings.

highlightClass:
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.

highlightTyped:
Wether to highlight (style) typed text on items. Default is true.

label:
Where to find the label on your source. The label is what will be shown on each item in the autocomplete list.

maximumItems:
How many items you want to show when the autocomplete is displayed. Default is 5. Set to 0 to display all available items.

onSelectItem:
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:

{ value: value, label: label }  

Note that you don't have to use this callback to set the text in the textfield, this is done automatically.

source:
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:

{ "label1": 1, "label2": 2, ...}

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.

treshold:
The number of characters that need to be typed on the input in order to trigger the autocomplete. Default is 4.

value:
Where to find the value on your source.

How it works

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.

Contributions

Feel free to open an issue or add a pull request. Anytime. Really, I mean it.

Also, if you like my work, I'll let you know that I love coffee. *wink wink nudge nudge*

bootstrap-4-autocomplete's People

Contributors

aurelien-roy avatar honatas avatar jonatasdiscover avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

bootstrap-4-autocomplete's Issues

Handling values not found in source array

For my usecase input, that's being typed in and is not found in source array, should be offered in suggestions too (in most cases it will be just single option after complete name of city is typed in), then after picking it, it should be handled by separate callback. That would be ideal solution.

In my case, I have limited ammount of available cities. If the typed in city is not in the list, it falls into separate shipping zone. I need to handle that, so I will have to make a workaround for this. It would be great if this situation was handled directly by your component.

Option to fetch source by ajax request

Looking for the following functionality:

  1. User types text
  2. Fetch request to server for autocomplete items
  3. User types more text
  4. Another fetch request for updated items

Multi word search

One thing it seems no one has and that is also with jquery autocomplete is multi word search. Say in your example, if I do bo au ex, it would find anything matching all those words. It is a nice way to whittle down a list matching multiple things. I made updates to your JS to do this. Feel free to implement them to your core if you like.

attached is the updated file.
ac.zip

Reposition list when items are shown above input field

When there is not enough place below the input field, the list with the suggestions is correctly placed above the input field. While typing, the list shrinks, but the top left position keeps its place, so there is a growing gap between the list and the input field.

This can be easily overcome by calling update after the open command on line 104.

this.off('keyup.autocomplete').keyup('keyup.autocomplete', function () {
    if (createItems(_field, opts) > 0) {
        _field.dropdown('show');
        _field.dropdown('update'); // <--- This updates the position of the list
    }

External file with content

Hello!

Your autocomplete is awesome and works great!

But I have an issue that I can't handle. I want to load the data from external file somewhere on my server. Can you give me the advice how to do that?

Thank you!

List not being hidden after selection

Thanks for this component, it's really good. I have a weird issue - the autocomplete list appears ok, and when I select an item the text field is updated. The list itself is not disappearing though. Console isn't showing any errors, not sure how to debug?

How to make AJAX URL working with autocomplete

Hello @Honatas

One more issue I'm facing ATM and would appreciate your help. I tried every way you mentioned at https://bootstrap-autocomplete.readthedocs.io/en/latest/ regarding how to make AJAX URL working with autocomplete but somehow that isn't helping. Can you please check and provide me some guidance about how to make it working. I've made a JSFiddle as well - https://jsfiddle.net/ae0o5fzy/.

Below is code I'm trying with:

$(this).autocomplete({
                resolverSettings: {
                    url: 'http://api.dev.phoenix.com/v1/en/users/autocomplete/email'
                },
                treshold: 2,
                onSelectItem: function(item, element) {
                    let input = $(element).data('value-input');
                    $('#'+input).val(item.value);
                }
            });

Please guide.

Many thanks,
Hiren

Keyboard Arrows Throwing Console Errors When Pressed

Hi,
I am using this library with Bootstrap v5.1.3 and have noticed errors in the console when pressing the arrow keys to access the dropdown menu generated by autocomplete.

Uncaught TypeError: Cannot read properties of undefined (reading 'nextElementSibling')
at Object.next (selector-engine.js:63:24)
at hi._getMenuElement (dropdown.js:270:27)
at new hi (dropdown.js:103:23)
at hi.getOrCreateInstance (base-component.js:55:41)
at HTMLDivElement.dataApiKeydownHandler (dropdown.js:453:31)
at HTMLDocument.n (event-handler.js:119:21)
next @ selector-engine.js:63
_getMenuElement @ dropdown.js:270
hi @ dropdown.js:103
getOrCreateInstance @ base-component.js:55
dataApiKeydownHandler @ dropdown.js:453
n @ event-handler.js:119

However, the tab key works fine.
Tested on Chrome 110.0.5481.178 and Firefox 111.0.1 on Windows 10

Three extra options

Hello.

This component is really easy to use and expand, well... In my repo i have expanded version of this component.
I add three configurable options. Maybe you like it πŸ‘

The first is the ability to add a class to the dropdown-menu item created by the component. This enables the creation of e.g. a scrolling drop-down list.
Option: class
Default: (empty string)

The second option is to allow a string comparison from the beginning. Uses the startsWith method to compare, not indexOf :) Simple, but very useful.
Option: startWith
Default: false

The third option is a fetchSource callback function to get autocomplete data.
In my fork, I have included a broader description and an example of use (is a bit stupid: P but shows, how to use it)
Option: fetchSource

I also added the ability to display all possible matching answers by setting the maximumItems value to 0 (zero). Useful when we use the class setting for dropdown-menu, e.g .:
CSS

.autocomplete {
  height:200px;
  overflow-y:auto;
}

JS

    $('#input').autocomplete({
        source: src,
        highlightClass: 'text-danger',
        treshold: 1,
        maximumItems: 0,
        class: 'autocomplete'
    });

Change the format source?

Hi, I need to use your component for my final project, but the source has to be an array. Could this be possible? I was trying for hours but I don't get it. Thanks.

source from database in json format

Hi,

I'm struggling with the source option of your autocomplete, I hope you can help me solve the problem
When I provide the source from the example

{
"Bootstrap 4 Autocomplete example": 1,
"Best example in the world": 2,
"Bootstrap 4 Autocomplete is very nice": 3,
"It contains neatly arranged example items": 4,
"With many autocomplete values": 5,
"And it uses default Bootstrap 4 components": 6,
"You can use this example to test": 7,
}

the autocomplete works.

However, when the source is a url
$(function() {$("#table_name").autocomplete({source: "{{=URL('jsonsource', 'name_autocomplete')}}"});});
returning options in the following format:

0: "Bootstrap 4 Autocomplete example"
1: "Best example in the world"
2: "Bootstrap 4 Autocomplete is very nice"

the autocomplete no longer work. I guess I have to set the label and value options, but I have not been able to figure out how.

Thanks in advance for your help.

Annet

Demos

Live demos will help attract more people

How to use the autocomplete in a form context?

I was wondering how to use your autocomplete field in a form context. Means: How to get the selected value of the autocomplate field when calling .serializeArray() of the form element and how to set the value when patching the form with stored values.
Thanks!

remote data

Hi is there any issue using data from an ajax request? I am not having success.

It would be helpful to have an index parameter

If the user of the plugin creates multiple instances of an input text box with autocomplete, there appears to be no way to tell the callback which instance on which to take action. In my use, I will have an unconstrained number of input text boxes with autocomplete, created as Instances of a Class. Each Instance has a unique index number associated with the enclosing div.

Solution: I'm going to send a pull request to do the following:

I suggest adding an additional option to identify the ID of the parent of the text box. I added in opts.onSelectItem one line, parentIDIndex: opts.parentIDIndex.

Armed with this, I can iterate through my Array for my search box IDs:

for (i=1; i < Array.length; i++){
  $(`#${Array[i].searchBoxID}`).autocomplete({
    source: tzNamesObject,
    onSelectItem: onSelectItem,
    highlightTyped: false,
    threshold: 3,
    parentIDIndex: i  
  });
};

And then in the onSelectItem callback I can set values unique to each ID:

function onSelectItem(item){
  Array[item.parentIDIndex].location = `${item.value}`;  
}

Use with JSON Array?

I am trying to find a way to use this with JSON arrays containing objects. The docs say you can use any format you want as long as you specify the value and labels, but does not go into any detail on how to do so. Could you elaborate on this?

How to get current element in onSelectItem callback function

Hello @Honatas ,

Can you please help with this and guide how to get current element where any autocomplete option is chosen. Have googled a lot and tried on my own but somehow I'm not able to figure that out. Below is the code:

$('input[type="text"].autocomplete').autocomplete({
            source: src,
            treshold: 2,
            onSelectItem: function(item) {
                console.log(item.value);
                console.log($(this));
                console.log($(this).find('input'));
                console.log(this);
            }
        });

The idea is that there can be more than one autocomplete control in a page and we need to get current control in onSelectItem callback function.

Thanks.

External source data

How can I get data written in autocomplete and make source data from an external file?

$('#myAutocomplete').on('input keyup', function() {
    var query = $(this).val();
    if (query.length > 2)
    {
        $.ajax({
            url:"/search.php",
            data: query,            
            dataType:"json",
            cache: false,
            processData:false,
            type:"POST",
            success: function (data) {
                $('#myAutocomplete').autocomplete({
                    source: data,
                    maximumItems: 10,
                    treshold: 2      
                });
               }
        });
    }   

});

Show autocomplete list at typed order

How can I show autocomplete list just for typed characters in order?

If I have,
src = ["name":"foo", "name":"boo", "name":"off", "name":"ok"]
treshold: 1
and I typed: "O"

output is: foo, boo, off, ok

I needed output just: off, ok

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.