Search code examples
javascriptmaterialize

Cant get the values from materializecss MultiSelect


I would like to read the values ​​with js from a multiselect. in the documentation of materializecss one should use .getSelectedValues ​​().

The console tells me now that the function is not working. I hope you can continue helping me there.

const selector = document.querySelectorAll('.funcselect');
const instanceSelector = M.FormSelect.init(selector);

function submitform() {
    // some other form to variables stuff

    var funcs = instanceSelector.getSelectedValues();

    // some xrh stuff

}

This is as basic as the code is constructed.

and here the console log:

js.js:21 Uncaught TypeError: instanceSelector.getSelectedValues is not a function

I hope someone can help me.

The documentation of the selector: https://materializecss.com/select.html


Solution

  • You need onChange event to handle the changes of your select.

    <div class="container row">
        <div class="input-field col s12">
            <select multiple>
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
            </select>
            <label>Materialize Multiple Select</label>
        </div>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var elems = document.querySelector('select');
            elems.onchange = selectThem;
            var instances = M.FormSelect.init(elems);
            function selectThem() {
                var selectedOne = instances.getSelectedValues();
                console.log(selectedOne);
            }
        });
    </script>
    

    change event - MDN

    Select - Materialize