From da5f50b17998263ca981a04bc555544e5c10f9e2 Mon Sep 17 00:00:00 2001 From: Xon <635541+Xon@users.noreply.github.com> Date: Thu, 5 Sep 2024 03:03:49 +0800 Subject: [PATCH] `duplicateItemsAllowed` option is now respected by `setChoices()` method. Resolves #855 --- CHANGELOG.md | 1 + src/scripts/choices.ts | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48c18355..96ad4d46 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 78be45d4..471836e3 100644 --- a/src/scripts/choices.ts +++ b/src/scripts/choices.ts @@ -2067,12 +2067,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; }