Floating label textとは
初期状態ではラベル名がプレースホルダとして表示され、テキスト入力するとプレースホルダの文字が上に浮き上がりラベルになるテキスト入力フィールドです。
コード:
<!-- Textfield with Floating Label -->
<form action="#">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="sample3">
<label class="mdl-textfield__label" for="sample3">Text...</label>
</div>
</form>
公式ページのリファレンス
https://getmdl.io/components/index.html#textfields-section
JavaScriptから値を変更した場合の注意
テキスト欄を単純に
document.querySelector('#sample3').value = 'hello';
のように変更しただけだと
のようにプレースホルダと入力文字が重なってしまいます。
対応
// MaterialTextfieldのchangeメソッドでテキストを変更
document.querySelector('#sample3').parentNode.MaterialTextfield.change('hello');
または
// テキストを変更した後でMaterialTextfieldのcheckDirtyメソッドを呼び出す。
document.querySelector('#sample3').value = 'hello';
document.querySelector('#sample3').parentNode.MaterialTextfield.checkDirty();
のように記述すると期待通りの動きとなります。
以下、サンプルコード。
https://jsfiddle.net/rhikos/t1eb0tp4/
参考にしたサイト
Floating label does not activate if a value is inserted to textarea/textbox
https://github.com/google/material-design-lite/issues/1287
Textfield placeholder label isn't updated when programmatically setting value
https://github.com/google/material-design-lite/issues/1319