Skip to content

[Bug]: Autocomplete selectOption does nothing #479

@ygorma

Description

@ygorma

Before submitting...

Context

Simply selectOption(); does not select an option.

Current Behavior

No option gets selected.

Expected behavior

Autocomplete loaded with an option selected. It would be perfect if there was an autocomplete initialization option which requires the id and do all the rest for us. Like:

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.autocomplete');
    var instances = M.Autocomplete.init(elems, {
      // specify options here
      minLength: 0, // shows instantly
      data: [
        {id: 12, text: "Apple"},
        {id: 13, text: "Microsoft"},
        {id: 42, text: "Google", image: 'http://placehold.it/250x250'}
      ],
      defaultOption: 12
    });
  });

Possible Solutions or Causes

Using this code to make it work.

selectOption(id) {
    const entry = this.options.data.find((item) => item.id == id);
    if (this.options.isMultiSelect) {
        const li = this.container.querySelector('li[data-id="' + id + '"]');
        const checkbox = li.querySelector('input[type="checkbox"]');
        checkbox.checked = !checkbox.checked;
        if (checkbox.checked)
            this.selectedValues.push(entry);
        else
            this.selectedValues = this.selectedValues.filter((selectedEntry) => selectedEntry.id !== entry.id);
        this.el.focus();
    }
    else {
        // Single-Select
        this.selectedValues = [entry];
        this._refreshInputText();
        this._resetAutocomplete();
        this.close();
    }
    this._updateSelectedInfo();
    this._triggerChanged();
}

Steps to reproduce

<script>

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('[id="1.id_modelo.autocomplete"]');
    var instances = M.Autocomplete.init(elems, {
      // specify options here
      minLength: 0, // shows instantly
      data: [
        {id: 2, text: "Teste"},
        {id: 3, text: "Parecer"}
      ]    
    });

    const autocomplete = document.querySelector('[id="1.id_modelo.autocomplete"]');
    let instance = M.Autocomplete.getInstance(autocomplete);
    instance.selectOption(2);

  });

</script>

Your Environment

  • Version used: Materialize v2.0.4
  • Browser Name and version: Edge 125.0.2535.51
  • Operating System and version (desktop or mobile): Windows 10
  • Additional information you want to tell us: N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions