Issue
How to append options to an existing initialized ChoicesJS instance?
Given the following HTML:
<select id="random-select"></select>
<button onclick="append()">
Append new data do select
</button>
And the following JS:
// initializes the plugin
function init()
{
const data =
{
removeItemButton: true,
duplicateItemsAllowed: false,
searchEnabled: true,
searchChoices: true,
};
const el = document.getElementById('random-select');
new Choices(el, data);
}
function append()
{
// How to append to existing element already initialized?
const el = document.getElementById('random-select');
// DOESN'T WORK
el.setChoices([{ value: 1, label: 'test' }]);
// DOESN'T WORK
el.choices.setValue([{ value: 1, label: 'test' }]);
}
Both el.setChoices and el.choices.setValue give an error:
setChoices is not a function
Cannot read properties of undefined (reading 'setValue')"
Check the JSFiddle.
Solution
According to the source code documentation on GitHub, setChoices is an instance method of the Choices class, so you'd need to invoke it as such.
const choicesInstance = new Choices(/* ... */);
choicesInstance.setChoices(/* ... */);
Here's an example based on the documentation and the code you provided:
const choices = new Choices(
document.getElementById("random-select"),
{
// allowHTML: true, // uncomment to suppress warning message
removeItemButton: true,
duplicateItemsAllowed: false,
searchEnabled: true,
searchChoices: true,
},
);
const append = () => choices.setChoices([{ value: 1, label: "test" }]);
document.getElementById("append-choices").addEventListener("click", append);
<!-- Include Choices CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js@10.2.0/public/assets/styles/choices.min.css" />
<!-- Include Choices JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/choices.js@10.2.0/public/assets/scripts/choices.min.js"></script>
<select id="random-select"></select>
<button id="append-choices">Append new data do select</button>
Answered By - jsejcksn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.