Search code examples
javascriptjquerymaterialize

How to replace a Materialize Select with Text-Input dynamically?


I'm trying to elicit a change from a Materialize select to a text[input] of input when the user clicks on Other

I've tried using .replaceWith(), instance.destroy();, and $(this).remove() all to no avail.

HTML:

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<h5>Materialize select</h5>


<div class="row">
 <div class="input-field col s12">
   <i class="material-icons prefix">device_hub</i>
   <select id="mySelect" class="change_select_to_text_on_other">
     <option value=""  selected>Choose "Other" to trigger!</option>
     <option value="1">Option 1</option>
     <option value="2">Option 2</option>
     <option value="other">Other</option>
   </select>
    <!--This is what I would like replace the select option with when other is clicked!:
    <input id="first_name" type="text" class="validate">
    <label for="first_name">Make your own selection!</label-->
 </div>
</div>

JS:

var $select1 = $('#mySelect');

$select1.material_select();
$select1.on('change', function (e) {
    if(e.target.value == 'other'){
    $( this ).replaceWith( "<h2>New heading</h2>" );
    var instance = M.FormSelect.getInstance($(this));
    instance.destroy();
  }
});

Fiddle

When the user clicks on other option the select gets replaced with a text input.

Thanks!


Solution

  • Is this close to what you want? I used a newer version of materialize.js

    https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js

    So I used $select1.formSelect(); instead of $select1.material_select();

    The complete code:

    $(function () {
        var $select1 = $('#mySelect');
    
        $select1.formSelect();
        $select1.on('change', function (e) {
    
            if (e.target.value == 'other') {
                $(this).replaceWith(`<input id="first_name" type="text" class="validate">
                <label for="first_name">Make your own selection!</label>`);
                $( ".select-dropdown.dropdown-trigger" ).remove();
                $( ".caret" ).remove();
    
            }
        });
    })