Search code examples
javascriptmaterialize

Set value of drop down select with Materialize.css 1.0.0 without jQuery


In my project, I save the values of the select elements and set them on page load to what the user last selected. This used to work by just setting the .value = "x" but now I can't set the values, I can only get them with instance.getSelectedValues(); as per the Materialize docs?

const selectedCategory = document.querySelector('#category');
const materializeSelectedCategory = M.FormSelect.init(selectedCategory);

... then on document ready

materializeSelectedCategory.value = "SET VALUE"; // This does not work...

Can't figure out how to set the values of the Materialize.css drop downs. I use multiple.

I am NOT using jQuery.


Solution

  • Can't figure out how to set the values of the Materialize.css drop downs. materializeSelectedCategory.value = "SET VALUE"; // This does not work...

    You need to use selectedCategory and dispatch change event:

    selectedCategory.value = "1";
    if (typeof(Event) === 'function') {
        var event = new Event('change');
    } else {  // for IE11
        var event = document.createEvent('Event');
        event.initEvent('change', true, true);
    }
    selectedCategory.dispatchEvent(event);
    

    const selectedCategory = document.querySelector('#category');
    const materializeSelectedCategory = M.FormSelect.init(selectedCategory);
    
    selectedCategory.value = "1";
    if(typeof(Event) === 'function') {
        var event = new Event('change');
    }else{
        var event = document.createEvent('Event');
        event.initEvent('change', true, true);
    }
    selectedCategory.dispatchEvent(event);
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
    
    
    <div class="input-field col s12">
        <select id="category">
            <option value="" disabled selected>Choose your option</option>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
        </select>
        <label>Materialize Select</label>
    </div>