1.10.0 • Published 1 year ago

select-4 v1.10.0

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

select4

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

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:

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:

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

Options

OptionDescriptionType
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
multipleWhether multiple selection is allowedboolean
maxItemsMax number of results to shownumber
whenEmptyTemplateHTML to display when there are no itemsstring
whenErrorTemplateHTML to display when there was an error fetching from the data sourcefunction (error: any) => string
valueAdapterA 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
suggestionsRendererCustom 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
valuesRendererFunction called to render values. Use this if you want to override the default values list item creation.function (list: []any, instance) => void
filterInputElementFunction to setup the filter input. For example, input => input.classList.add('form-control')function (input: HTMLInputElement) => void
valueElementA 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
suggestionsContainerElementA function to setup the suggestions container div.function (container: HTMLElement) => void
suggestionItemElementA function to setup each suggestion html element.function (suggestionElt: HTMLElement) => void
valueTemplateHTML template string for each value item. For example, (i, _) => `<a href="${i.Link}">${i.Title}</a>`function (item, instance) => string
suggestionItemTemplateHTML template string for each suggestion item. For example, (i, _) => i.Titlefunction (item, instance) => string
busyAnimationWhether to animate the busy indicatorboolean

Events

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

OptionDescriptionType
onErrorError handler function, called when data source call throws an exceptionfunction (err: any, instance) => void
onChangeEvent 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 ClassDescription
select4-inputThe search input
select4-suggestionsSuggestions container panel
select4-suggest-itemIndividual suggested item
select4-valuesValues panel
select4-valueIndividual value item
select4-value-btnThe remove button for each value item
select4-busyThe busy indicator
select4-errorThe error panel
select4-no-resultThe container shown when there are no results

Development

To run samples:

npm run dev

To build everything:

npm run build
1.10.0

1 year ago

1.9.0

1 year ago

1.8.0

1 year ago

1.7.0

1 year ago

1.6.0

1 year ago

1.5.0

1 year ago

1.4.0

1 year ago

1.3.0

1 year ago

1.2.0

1 year ago

1.1.0

1 year ago