Choices-js / Choices

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

setChoiceByValue success but item is not highlighted #1130

Closed vttkrk closed 10 months ago

vttkrk commented 10 months ago

Describe the bug I tried to use method setChoiceByValue to programmatically set the selected item. It works correctly when you look at the UI (dropdown not shown) and getValue() from Choice instance. However when you click to show the dropdown, the selected item is not highlighted.

To Reproduce


<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css"
    />
    <div>
      <label v-if="label" class="form-label">label here</label>
      <select
        id="se-dropdown"
        class="form-control"
        name="choices-button"
      ></select>
    </div>
    <button id="set-choice-by-value">setChoiceByValue('yahoo')</button>
    <script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
    <script>
      const searchEngineChoiceList = [
        {
          id: 1,
          value: "google",
          label: "Google",
        },
        {
          id: 2,
          value: "yahoo",
          label: "Yahoo",
        },
        {
          id: 3,
          value: "bing",
          label: "Bing",
        },
      ];
      const element = document.getElementById("se-dropdown");
      const choices = new Choices(element);
      choices.setChoices(searchEngineChoiceList);
      const setChoiceBtn = document.getElementById("set-choice-by-value");
      setChoiceBtn.addEventListener("click", function () {
        choices.setChoiceByValue("yahoo");
      });
    </script>
  </body>
</html>```

**Expected behavior**
item which is selected by setChoiceByValue should be highlighted when the dropdown is shown, just like manually click on item.

**Screenshots**
![image](https://github.com/Choices-js/Choices/assets/138220768/5e0b8703-6973-4972-8abd-715edfe614ba)
![image](https://github.com/Choices-js/Choices/assets/138220768/13765896-b14f-499d-abac-a5619011eaa9)

**Desktop (please complete the following information):**
 - OS: Windows 10
 - Browser: Edge
 - Version: 116.0.1938.69 (64 bit)
vttkrk commented 10 months ago

Found a workaround solution here https://github.com/Choices-js/Choices/issues/586