From 0864f2d8193b5e864d745c116b1b13b31fb96e5f 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 1/2] `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 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; } From 79b795f561a367d79358095e437a444fa3b0d228 Mon Sep 17 00:00:00 2001 From: Xon <635541+Xon@users.noreply.github.com> Date: Thu, 5 Sep 2024 03:14:18 +0800 Subject: [PATCH 2/2] Commit clearStore change --- src/scripts/choices.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/scripts/choices.ts b/src/scripts/choices.ts index 7f013a9a..2005cecd 100644 --- a/src/scripts/choices.ts +++ b/src/scripts/choices.ts @@ -853,13 +853,14 @@ class Choices { return this; } - clearStore(): this { + clearStore(clearOptions: boolean = true): this { this._stopSearch(); - this.passedElement.element.replaceChildren(''); + if (clearOptions) { + this.passedElement.element.replaceChildren(''); + } this.itemList.element.replaceChildren(''); this.choiceList.element.replaceChildren(''); - this._stopSearch(); this._store.reset(); this._lastAddedChoiceId = 0; this._lastAddedGroupId = 0;