select-4
TypeScript icon, indicating that this package has built-in type declarations

1.10.0 • Public • Published

select4

Zero dependency (~1 KiB) autocomplete and multiselect control for the web. Inspired by select2 and select3.

In Action

Installation

To install, using npm:

npm i select-4

Usage

To turn a select input into select4, use:

import {select4} from 'select-4'
import "select-4/dist/style-bootstrap.css" // with bootstrap 5 styles; Otherwise just use style.css

select4(selectInput, options)

Quick Start

If you have got an HTML select control as:

<select name="select-fruits" id="select-fruits"></select>

...

const mySelect = document.getElementById('select-fruits')

then you can transform it into a select4 using:

import {select4} from 'select-4'
import "select-4/dist/style.css"

select4(mySelect, {
    dataSource: ['Apple', 'Orange', 'Banana', 'Mango', 'Guava', 'Strawberry'],
})

You can see the values from your original select input:

const values = Array.from(mySelect.querySelectorAll("option:checked"), e => e.value);

To listen to changes:

select4(mySelect,{
    dataSource: ...,
    onChange: selections => console.log('Selected:', selections)
})

If you have a remote REST API as a datasource, use:

select4(document.getElementById('search-wikipedia'), {
    dataSource: async (filter) => {
        const res = await fetch('https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=' + filter)
        if (res.ok) {
            const result = (await res.json())
            return result[1].map((i, index) => ({title: i, link: result[3][index]}))
        }
        return []
    },
    valueTemplate: (item, _) => `<a href="${item.link}">${item.title}</a>`,
    suggestionItemTemplate: (item, _) => item.title,
})

The above code with the bootstrap styling would result:

In Action

An even more elaborate example would be an XKCD comics search. Configure it as:

valueTemplate: (item, _) => `<a href="${item.link}">${item.title}</a>`,
suggestionItemTemplate: (item, _) =>
    `
    <hr>
    <h4 style="margin: 0">
        ${item.title}
        &nbsp;<small style="border: 1px solid black; background: grey; color: white">${item.year}</small>
    </h4>            
    <div>
        <img src="${item.img}" height="48px">
    </div>`

which would result in something like:

In Action

You can find examples in src/examples.ts file.

Options

Option Description Type
dataSource* Function called to search for values based on search key. You can also supply a simple array, or use the staticDataSource() method. Array or async function (searchKey: string) => []any
multiple Whether multiple selection is allowed boolean
maxItems Max number of results to show number
whenEmptyTemplate HTML to display when there are no items string
whenErrorTemplate HTML to display when there was an error fetching from the data source function (error: any) => string
valueAdapter A map function called to extract the final value when a search result item is selected. For example, i => ({key: i.Name, value: i.Id}) function (item) => any
suggestionsRenderer Custom function to be called to render search results. Use this if you want to override the default suggestions panel creation. function (list: []any, instance) => void
valuesRenderer Function called to render values. Use this if you want to override the default values list item creation. function (list: []any, instance) => void
filterInputElement Function to setup the filter input. For example, input => input.classList.add('form-control') function (input: HTMLInputElement) => void
valueElement A function to setup each value html element. For example, (i, elt) => elt.setAttribute('style', 'color: red; border: 1px solid green;') function (value: any, element: HTMLElement) => void
suggestionsContainerElement A function to setup the suggestions container div. function (container: HTMLElement) => void
suggestionItemElement A function to setup each suggestion html element. function (suggestionElt: HTMLElement) => void
valueTemplate HTML template string for each value item. For example, (i, _) => `<a href="${i.Link}">${i.Title}</a>` function (item, instance) => string
suggestionItemTemplate HTML template string for each suggestion item. For example, (i, _) => i.Title function (item, instance) => string
busyAnimation Whether to animate the busy indicator boolean

Events

You can handle the following events by specifying in the config options.

Option Description Type
onError Error handler function, called when data source call throws an exception function (err: any, instance) => void
onChange Event triggered when selection changes. For example, selected_items => console.log('change', selected_items) function (items: Array) => void

Styling

Default styles are included in style.css file. You can add a css for the following classes:

Css Class Description
select4-input The search input
select4-suggestions Suggestions container panel
select4-suggest-item Individual suggested item
select4-values Values panel
select4-value Individual value item
select4-value-btn The remove button for each value item
select4-busy The busy indicator
select4-error The error panel
select4-no-result The container shown when there are no results

Development

To run samples:

npm run dev

To build everything:

npm run build

Package Sidebar

Install

npm i select-4

Weekly Downloads

0

Version

1.10.0

License

ISC

Unpacked Size

166 kB

Total Files

15

Last publish

Collaborators

  • lgirma