Custom element for selecting multiple items using an input and datalist to suggest options.
Delete items with Backspace or by tapping/clicking an item's × icon.
| View and remix this project live on Glitch |
|---|
-
Add multi-input.js to your project and link to it:
<script src="multi-input.js"></script>
-
Wrap an
inputand adatalistin a<multi-input>(see index.html):<multi-input> <input list="speakers"> <datalist id="speakers"> <option value="Banquo"></option> <option value="Celia"></option> ... </datalist> </multi-input>
-
Get selected values like this (see script.js):
const getButton = document.getElementById('get'); const multiInput = document.querySelector('multi-input'); getButton.onclick = () => { console.log(multiInput.getValues()); }
Sure.
There are several custom properties:
--multi-input-border
--multi-input-item-bg-color
--multi-input-item-border
--multi-input-item-font-size
--multi-input-input-font-size
Style components like this:
multi-input {
--multi-input-border: 2px solid red;
}Two selectors have been added outside the shadow DOM using a multi-input selector:
::slotted(input)::-webkit-calendar-picker-indicatordoesn't work in any browser.::slotted(div.item)::afterdoesn't work in Safari.
Custom elements are widely supported by modern browsers.
However, <multi-input> simply wraps an input element that has a datalist, so behaviour will degrade gracefully to a 'normal' datalist experience in browsers without custom element support.
The datalist element is supported by all modern browsers.
If your target browser doesn't support datalist, behaviour will fall back to the plain old input experience.