Locohost
Locohost

Reputation: 1702

Materialize Select JavaScript: Cannot initialize .formSelect not a function, .append not a function

As you can see by the comments in code snippets below, I've tried everything that seems to make sense. I find the Materialize documentation very old and lacking details and working code examples. I've found 1 or 2 posts here on SO and I'm trying (see commented code) the suggestions. I cannot make this work.

Can you see what I'm doing wrong?

Thank you, thank you, thank you for helping :-)

Here is the Html content...

<div class="container">
    <div class="row">
        <div class="input-field col s12">
            <select id="collName">
                <option>( Choose collection... )</option>
            </select>
        </div>
        <div class="input-field col s12">
            <select id="query">
                <option>( Choose query... )</option>
            </select>
        </div>
    </div>
    <div class="row">
        <div id="status" class="col s12">Ready</div>
    </div>
    <div class="row">
        <div id="collections" class="col s4">4 columns</div>
        <div id="container" class="col s8"></div>
    </div>
</div>

Here is JavaScript code...

document.addEventListener('DOMContentLoaded', function () {
    // const elems = document.querySelectorAll('select');
    // const options = {};
    // const instances = M.FormSelect.init(elems, options);

    const optionsColls = [];
    config.collections.forEach(c => {
        optionsColls.push("<option>" + c + "</option")
    });

    const elemCollName = document.getElementById('collName');
    collName = M.FormSelect.init(elemCollName, {});
    //collName = M.FormSelect.getInstance(elemCollName);
    // collName.empty();
    collName.formSelect();
    collName.append(optionsColls);

    // config.collections.forEach(coll => {
    //  collName.options.add(new Option(coll, coll));
    // });

});

Upvotes: 1

Views: 1371

Answers (1)

Locohost
Locohost

Reputation: 1702

The following does work when loading/init'ing the Select...

document.addEventListener('DOMContentLoaded', function () {
    const elemCollName = document.getElementById('collName');
    config.collections.forEach(c => {
        elemCollName.options.add(new Option(c, c));
    });
    M.FormSelect.init(elemCollName);
});

This also seems to work fine when you're dynamically loading Select option lists in events. Just always call the .init() after you modify your Select.

Upvotes: 1

Related Questions