Choices-js / Choices

A vanilla JS customisable select box/text input plugin ⚡️
https://choices-js.github.io/Choices/
MIT License
6.06k stars 598 forks source link

Destroy does not preserve the selected value #1088

Open tagliala opened 1 year ago

tagliala commented 1 year ago

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:

  1. Go to https://jsfiddle.net/tagliala/yetk9sgh/3/
  2. Click on the page to invoke destroy

Expected behavior Option 3 (selected) selected

Screenshots n/a

Desktop (please complete the following information):

Smartphone (please complete the following information):

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')
    })
  }
creativetags commented 1 month ago

I've run into this problem too. Would be great to have a way to destroy() and keep selected values.