LoginSignup
6
6

More than 5 years have passed since last update.

Material Design Liteのfloating label textをJavaScriptから更新するときの注意

Last updated at Posted at 2016-10-22

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>

表示:
スクリーンショット 2016-10-22 11.19.32.png

公式ページのリファレンス
https://getmdl.io/components/index.html#textfields-section

JavaScriptから値を変更した場合の注意

テキスト欄を単純に

document.querySelector('#sample3').value = 'hello';

のように変更しただけだと
スクリーンショット 2016-10-22 11.34.01.png
のようにプレースホルダと入力文字が重なってしまいます。

対応

// 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

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6