LoginSignup
0
0

More than 5 years have passed since last update.

jsでinputのvalueに値を設定した際にMDLのフローティングラベルを有効にする

Posted at

テキストボックスにjsでvalueを設定した際、MDL(Material Design Lite)のフローティングラベルが効かなくて調べたので対応内容をメモ。

背景

エポック時間(ミリ秒<->時刻)変換ツールを作っていて、テキストボックスにjsで値をセットしたらMDLのフローティングラベルが効かず、プレースホルダーと値が重なってしまった。
changeイベントかと思い強制発火させてみたものの解消せず、ちょっとはまった。
Converter.png

対応

changeイベントはchangeイベントでもMaterialTextfield.change(hoge)で発火させてやる必要があった。

index.html
<section id="wrapper">
  <div class="title">Epoch Time</div>
  <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
    <input class="mdl-textfield__input" type="text" id="epoch-milli" name="epoch-milli">
    <label class="mdl-textfield__label" for="epoch-milli">Epoch millisec...</label>
  </div>
  <div class="btn-area">
    <div id="to-epoch-milli" class="icon material-icons btn">arrow_upward</div>
    <span class="mdl-tooltip" for="to-epoch-milli">To epoch millisec</span>
    <div id="to-epoch-time" class="icon material-icons btn">arrow_downward</div>
    <span class="mdl-tooltip" for="to-epoch-time">To epoch time</span>
  </div>
  <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
    <input class="mdl-textfield__input" type="text" id="epoch-time" name="epoch-time">
    <label class="mdl-textfield__label" for="epoch-time">Epoch time...</label>
  </div>
</section>
index.js
document.getElementById('to-epoch-milli').addEventListener('click', () => {
  const epochTime = document.getElementById('epoch-time').value;
  const epochMilli = moment(epochTime, DATE_FORMAT);
  const $el = document.getElementById('epoch-milli');
  $el.parentElement.MaterialTextfield.change(epochMilli.format("x"));
  $el.focus();
  $el.select();
});

これでうまく動いた。
Converter-2.png

ちなみに https://codepen.io/anon/pen/ZWerBY のサンプルがとてもわかりやすかった。

参考

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