Categories
JavaScript Answers

How to manually add some items with Selectize.js?

Spread the love

To manually add items to a Selectize.js dropdown, you can use the addOption() method.

To do this we can try the following.

1. Include Selectize.js

Make sure you have included Selectize.js in your HTML file. You can either download it and include it locally or use a CDN.

<link rel="stylesheet" href="path/to/selectize.css">
<script src="path/to/selectize.js"></script>

2. Create HTML Select Element

Create a select element in your HTML file and give it an ID.

<select id="mySelect"></select>

3. Initialize Selectize

Use JavaScript to initialize the Selectize plugin on your select element.

var mySelect = $('#mySelect').selectize({
    create: true,
    sortField: 'text'
});

4. Add Items Programmatically

You can then add items to the select element using the addOption() method.

var selectize = mySelect[0].selectize;

// Add items manually
selectize.addOption({value: '1', text: 'Option 1'});
selectize.addOption({value: '2', text: 'Option 2'});

You can call addOption() as many times as needed to add multiple items.

5. Trigger Dropdown Refresh

After adding options, you might need to refresh the dropdown to reflect the changes. You can do this by calling the refreshOptions() method.

selectize.refreshOptions();

That’s it! You’ve now manually added items to a Selectize.js dropdown. This can be useful when you want to dynamically populate the dropdown based on user actions or data from an external source.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *