Dynamic Multi-select Dropdown In Vanilla JavaScript – MultiSelect

Category: Form , Javascript | March 23, 2019
Author: dotburo
Views Total: 632
Official Page: Go to website
Last Update: March 23, 2019
License: MIT

Preview:

Dynamic Multi-select Dropdown In Vanilla JavaScript – MultiSelect

Description:

The MultiSelect JavaScript library generates a stylish select element from a JavaScript array that enables the user to select multiple items from the dropdown list.

How to use it:

Install & import.

# NPM
$ npm install @dotburo/multi-select --save
import MultiSelect from 'multi-select';

Or load the umd version in the document.

<script src="multi-select-umd.js"></script>

Load the necessary stylesheet in the document.

<link href="base.min.css" rel="stylesheet">

Create a container element for the multi-select dropdown.

<div class="multi-select"></div>

Insert items (options) into a JavaScript array (or an array of objects):

const myData = ['JavaScript', 'HTML5', 'CSS & CSS3', 'PHP', 'Object C', 'Python']

Attach the MultiSelect to the container element and specify the data source.

var multiSelect = new MultiSelect('.multi-select', {
    items: myData
});

Set the current item.

var multiSelect = new MultiSelect('.multi-select', {
    items: myData
    current: ['Python']
});

// or
multiSelect.setCurrent('Python');

Available customization options.

var multiSelect = new MultiSelect('.multi-select', {
    items: myData
    display: 'value', // the property to use
    current: null,
    parent: null, // parent element
    maxHeight: 0,
    sort: true, // sort the dropdown list
    order: 'desc', // or arc
    placeholder: 'Select items',
    more: '(+{X} more)'
});

Trigger an event when the value changed.

multiSelect.on('change', function (e) {
  console.log(e.detail, multiSelect.getCurrent());
});

API methods.

// toggle the multi-select dropdown
// false = show
multiSelect.toggle(true);

// get the element
multiSelect.getElement();

// get all the items
multiSelect.getItems();

// get the selected items
multiSelect.getCurrent();

// set the current items
multiSelect.setCurrent();

// find an item by value
multiSelect.findItem(value);

// destroy the library
multiSelect.remove();

Changelog:

03/23/2019

  • Small improvements

You Might Be Interested In:


3 thoughts on “Dynamic Multi-select Dropdown In Vanilla JavaScript – MultiSelect

  1. yaniv shmuel

    I try to put your two multi-select in one page and just the first one work correctly, the second one not work at all.

    Reply
  2. La Tortue Rose

    Same problem : not possible to have two multi-select in one page

    Reply

Leave a Reply