bluzky / nice-select2

A lightweight vanilla javascript library that replaces native select elements with customizable dropdowns
https://bluzky.github.io/nice-select2/
MIT License
370 stars 61 forks source link

Can you use AJAX to fill the result? #79

Open AttilioIurlaro opened 10 months ago

AttilioIurlaro commented 10 months ago

I have a lot of data (all the cities of my country) and I can't fill all the values. I want to use ajax when a user search into the search box How can I do it with nice-select 2?

OlegChuev commented 8 months ago

Hi @AttilioIurlaro! I hope you're doing great!

If this request is still relevant to you or any newcomers, you can easily do something like this

1) First, create your nice-select2 instance and add an event listener:

  const niceSelectInstance = new NiceSelect(yourElement)
  const inputField = niceSelectInstance.dropdown.querySelector('.nice-select-search')

  inputField.addEventListener('input', () => {
    fetchAjaxData(yourElement, niceSelectInstance)
  })

2) And now you can manipulate the instance of the nice-select2 in your callback, so you can do something like this:

  async fetchAjaxData (element, niceSelectInstance) {
    try {
      const reqPath = yourAjaxReqPath;
      const response = await fetch(reqPath, { headers: { accept: 'application/json' } });
      const data = await response.json();

      data.forEach((elem, i) => {
        element.options[i] = new Option(elem[0], elem[1]);
      });

      niceSelectInstance.update();
    } catch (error) {
      console.error(error);
      // Handle error if needed
    }
  }

I've attached GIF of how niceSelectInstance.update(); behaves, but on slightly different case 🙂 modal