Choices-js / Choices

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

Uncaught TypeError: Cannot read properties of undefined (reading 'removeLoadingState') #1041

Closed realnot closed 2 months ago

realnot commented 2 years ago

I have an empty dropdown that I need to populate with choices retrieved from server. This is the DOM

<!-- Input -->
<select name="birthday_province" data-choices="{&quot;renderChoiceLimit&quot;: 10}" class="form-select" required id="id_birthday_province">
  <option value="" selected>---------</option>
</select>

and this is the script

<script>
  $("#id_birthday_country").change(function () {
    var url = $("#resumeForm").attr("data-provinces-url");  // get the url of the `load_provinces` view
    var countryId = $(this).val();  // get the selected country ID from the HTML input

    $.ajax({                       // initialize an AJAX request
      url: url,                    // set the url of the request (= localhost:8000/resume/ajax/load-provinces/)
      data: {
        'country': countryId       // add the country id to the GET parameters
      },
      success: function (data) {
        // `data` is the return of the `load_provinces` view function
        const element = $("#id_birthday_province")[0]
        const choices = new Choices(element)
        choices.setChoices(
          [
            { value: 'One', label: 'Label One', disabled: true },
            { value: 'Two', label: 'Label Two', selected: true },
            { value: 'Three', label: 'Label Three' },
          ],
          'value',
          'label',
          false,
        );
      }
    });
  });
</script>

image

What I'm doing wrong here?

ankitwwt commented 2 years ago

@realnot

<script>
$("#id_birthday_country").change(function () {
    var url = $("#resumeForm").attr("data-provinces-url");
    var countryId = $(this).val();
    $.ajax({
        url: url,
        data: {
            'country': countryId
        },
        success: function (data) {
            const element = document.getElementById('id_birthday_province');
            const choices = new Choices(element);
            choices.setChoices([
                { value: 'One', label: 'Label One', disabled: true },
                { value: 'Two', label: 'Label Two', selected: true },
                { value: 'Three', label: 'Label Three' },
            ]);
        }
    });
});
</script>

Try to check with the above code.

casually-creative commented 1 year ago

You're getting this error because you are making a new choices on every change of the country field. This line const choices = new Choices(element) should be outside of the change handler so it only gets executed once.

Xon commented 2 months ago

A better error message will be generated as part of v11.0.0