bluzky/nice-select2

Can you use AJAX to fill the result?

Opened this issue · 1 comments

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?

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)
  })
  1. 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