Choices: Why is there no example of using XHR/Ajax?

Created on 17 Nov 2020  路  3Comments  路  Source: Choices-js/Choices

bug

Most helpful comment

If someone find this issue here is an example.

choices.passedElement.element.addEventListener(
    'search',
    debounce(async e => {
        const data = await jsonFetch(`${this.dataset.search}?q=${encodeURIComponent(e.detail.value)}`)
        this.choices.setChoices(data, this.dataset.value || 'value', this.dataset.label || 'label', true)
    }, 400)
)

You have to use setChoices to create your list of choices.

All 3 comments

If someone find this issue here is an example.

choices.passedElement.element.addEventListener(
    'search',
    debounce(async e => {
        const data = await jsonFetch(`${this.dataset.search}?q=${encodeURIComponent(e.detail.value)}`)
        this.choices.setChoices(data, this.dataset.value || 'value', this.dataset.label || 'label', true)
    }, 400)
)

You have to use setChoices to create your list of choices.

We are using it similar to the Example 2 in the Readme: https://github.com/jshjohnson/Choices#setchoiceschoices-value-label-replacechoices. Do you need more than that?

If you just want to load data from remote initially, there is a demo of that at https://joshuajohnson.co.uk/Choices/#choices-single-remove-xhr. The setChoices() also takes a function that returns the items which makes it easy to implement this without handling any events. See the docs for details.

This is the relevant code from the demo page:

        var singleXhrRemove = new Choices('#choices-single-remove-xhr', {
          removeItemButton: true,
          searchPlaceholderValue: "Search for a Smiths' record",
        }).setChoices(function(callback) {
          return fetch(
            'https://api.discogs.com/artists/83080/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW'
          )
            .then(function(res) {
              return res.json();
            })
            .then(function(data) {
              return data.releases.map(function(release) {
                return { label: release.title, value: release.title };
              });
            });
        });

I recommend using ES7 await instead of the .then() thought.

I agree, there could be an example that illustrates this more clearly.

If you need a live remote search (where the query is sent to the remote), go with the https://github.com/jshjohnson/Choices/issues/914#issuecomment-770261367.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ckotzbauer picture ckotzbauer  路  5Comments

michaelongithub picture michaelongithub  路  4Comments

alfonsoar picture alfonsoar  路  4Comments

jchamb picture jchamb  路  4Comments

sebastien-roch picture sebastien-roch  路  3Comments