Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can you use AJAX to fill the result? #79

Open
AttilioIurlaro opened this issue Jan 7, 2024 · 1 comment
Open

Can you use AJAX to fill the result? #79

AttilioIurlaro opened this issue Jan 7, 2024 · 1 comment

Comments

@AttilioIurlaro
Copy link

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
Copy link

OlegChuev commented Mar 6, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants