Choices
Choices copied to clipboard
Destroy does not preserve the selected value
Describe the bug
destroy
does not respect selected
value. This causes issues when using with libraries like Turbo and Stimulus, where you want to destroy()
when leaving the page or disconnecting the controller
To Reproduce Steps to reproduce the behavior:
- Go to https://jsfiddle.net/tagliala/yetk9sgh/3/
- Click on the page to invoke destroy
Expected behavior
Option 3 (selected)
selected
Screenshots n/a
Desktop (please complete the following information):
- OS: macOS
- Browser Chrome, Firefox, Safari
- Version 108, 108, 16.2
Smartphone (please complete the following information):
- Device: iPhone 12
- OS: iOS 16.2
- Browser Safari
- Version 16.2
Additional context Related to #1055
As a workaround for simple inputs, I'm using this in the disconnect()
controller
disconnect () {
// FIXME: workaround for Choices-js/Choices#1088
const selectedValues = this.choices._currentState.items.map((item) => item.value)
this.choices.destroy()
selectedValues.forEach((selectedValue) => {
const option = this.choicesTarget.querySelector(`option[value="${selectedValue}"]`)
if (!option) { return }
option.setAttribute('selected', 'selected')
})
}