Search code examples
jquerymaterialize

jQuery/Materialize: Changing select option back to disabled select on clear


I'm using a MaterializeCSS form, and I'm having an issue getting the select option to revert back to it's disabled "Choose your option" value when I clicked the Reset button.

I'm able to clear everything, even the Select option with what I have now, but cannot figure out how to get it clear back to it's disabled value.

<div class="row">
    <form class="col s12">
        <div class="row">
            <div class="input-field col s12">
                <input id="last_name" type="text" class="validate">
                <label for="last_name">Last Name</label>
            </div>
        </div>

        <div class="row">
            <div class="input-field col s12">
                <select class="icons" id="platform" name="platform">
                    <option value="None" class="grey-text text-darken-3" disabled selected>Choose your option</option>
                    <option value="PS4" data-icon="images/ps4.jpg" class="left circle">Playstation 4</option>
                    <option value="PC" data-icon="images/steam.ico" class="left circle">PC</option>
                    <option value="XBOX" data-icon="images/xbox.ico" class="left circle">XBox One</option>
                </select>
                <label>Platform:</label>
            </div>
        </div>

        <a class="waves-effect waves-light btn">Reset</a>
    </form>
</div>

Here's the JS

$(".btn").click(function(){
    $("form input").val("");
});

$('select').material_select();

Codepen


Solution

  • You have to reset both select element and material select:

    var select = $('select');
    
    $(".btn").click(function(){
        $("form input").val("");
    
        select.prop('selectedIndex', 0); //Sets the first option as selected
        select.material_select();        //Update material select
    });
    
    select.material_select();