PW Suggestions
Javascript library to autocomplete/suggest values in inputs. It has the following features:
- Follows the progressive enhancement strategy: if javascript fails, the web page keeps working
- Can get the values from
<datalist>
or ajax. - Support for
<optgroups>
. - Build with ES6.
- No default CSS styles provided (yes, it's a feature).
Install
Requirements:
- NPM or Yarn to install the package and the dependencies
- Webpack (or any other javascript loader)
npm install pw-suggestions
Usage
HTML
Let's start with the following html code:
Ivan Pablo María Alejandro
JS
Use javascript for a complete experience:
; //Get the inputconst input = document; //Generate the available results from the related <datalist>const source = input; //Generate the suggestions joining the input and the source valuesconst suggestions = input source;
API
constructor
Create a new instance of Suggestions
. The arguments are:
input
The input elementsource
An instance of one of the available sources (see below)
on
Register events in the page loader workflow. The available events are:
select
When the user select an option
suggestions;
off
Unregister one or all callbacks of an event
//unregister one callbacksuggestions; //unregister all callbackssuggestions;
destroy
Unbind all event listener and restore the inputs to the previous state.
The available sources
As you can see, the constructor of the class Suggestions
needs two arguments: the input and the source used to search and display the suggestions. There are different sources for different needs:
DatalistSource
: Get the source from the<datalist>
element associated to the input.AjaxSource
: Get the source from an ajax request returning a json with the data.
Example with ajax:
; const suggestions = document '/api/suggestions';
All sources have the following options:
Name | Type | Description |
---|---|---|
parent | Node |
The parent node in which the suggestions are inserted in the DOM. By default is document.body unless DatalistSource that uses the parent element of the <datalist> element. |
suggestions.render | function |
A function to customize the html of each suggestion. |
suggestions.label | string |
The object key used to generate the label of the suggestion. By default is label . |
suggestions.value | string |
The object key used to generate the value of the suggestion. By default is value . |
group.label | string |
The object key used to generate the label of the group of suggestion. By default is label . |
Example:
; const suggestions = document '/api/suggestions' parent: document suggestions: label: 'title' value: 'id' { return `<strong></strong>`; } ;
Demo
To run the demo, just clone this repository enter in the directory and execute:
npm installnpm start
You should see something in http://localhost:8080/