Choices-js / Choices

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

Provide an option to track options from underlying select element #1003

Open francoislehoux-okta opened 2 years ago

francoislehoux-okta commented 2 years ago

Is your feature request related to a problem? Please describe. There is currently no clear way to have choices track the options from the underlying select element. We can use .setChoices but we have to manually parse every. Most of this logic already exist within the constructor/init methods.

Say, you are using choicesjs within react, when the children changes dynamically, you want an easy way to have those reflected in the rendered component.

It seems this has been asked often but was never considered or OKd (issue getting automatically closed after X days).

Describe the solution you'd like Could be:

Describe alternatives you've considered This "works" but feels out of place when outside of the library itself.

const options: any[] = [];
if (choices.current.passedElement.options) {
  choices.current.passedElement.options.forEach((option) => {
    options.push({
      value: option.value,
      label: option.innerHTML,
      selected: !!option.selected,
      disabled: option.disabled || option.parentNode.disabled,
      placeholder:
        option.value === '' || option.hasAttribute('placeholder'),
      customProperties: option.dataset['custom-properties'],
    });
  });
}
choices.current.setChoices(options);
mtriff commented 2 years ago

I'm open to exploring this, I see why you'd want this functionality. I'd probably go with the refresh method route you mentioned.

How do you propose handling cases where a selected choice is no longer in the options of the underlying element?