Как динамически заменить Materialise Select на Text-Input? - PullRequest
0 голосов
/ 21 сентября 2019

Я пытаюсь добиться изменения от материализации select до text[input] ввода, когда пользователь нажимает Other

Я пытался использовать .replaceWith(), instance.destroy();и $(this).remove() все безрезультатно.

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();
  }
});

Скрипка

Когда пользователь нажимает на другую опцию, выберитезаменяется вводом текста.

Спасибо!

1 Ответ

1 голос
/ 22 сентября 2019

Это близко к тому, что вы хотите?Я использовал более новую версию materialize.js

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

Поэтому я использовал $select1.formSelect(); вместо $select1.material_select();

Полный код:

$(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();

        }
    });
})
...