diff --git a/CHANGELOG.md b/CHANGELOG.md index d6ad2f9e..576a94d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Features (from 11.0.0) * Pass `getClassNames` as the 3rd argument to `callbackOnCreateTemplates` callback +* `duplicateItemsAllowed` option is now respected by `setChoices()` method [#855](https://github.com/Choices-js/Choices/issues/855) ### Bug Fixes (from 11.0.0) * Fix choice disable state wasn't considered when showing the "no choices to choose from" notice diff --git a/src/scripts/choices.ts b/src/scripts/choices.ts index c5353b4f..7f013a9a 100644 --- a/src/scripts/choices.ts +++ b/src/scripts/choices.ts @@ -2078,12 +2078,20 @@ class Choices { throw new TypeError('Can not re-add a choice which has already been added'); } + const { config } = this; + if ( + (this._isSelectElement || !config.duplicateItemsAllowed) && + this._store.choices.find((c) => config.valueComparer(c.value, choice.value)) + ) { + return; + } + // Generate unique id, in-place update is required so chaining _addItem works as expected this._lastAddedChoiceId++; choice.id = this._lastAddedChoiceId; choice.elementId = `${this._baseId}-${this._idNames.itemChoice}-${choice.id}`; - const { prependValue, appendValue } = this.config; + const { prependValue, appendValue } = config; if (prependValue) { choice.value = prependValue + choice.value; }