テキストボックスにjsでvalueを設定した際、MDL(Material Design Lite)のフローティングラベルが効かなくて調べたので対応内容をメモ。
背景
エポック時間(ミリ秒<->時刻)変換ツール
を作っていて、テキストボックスにjsで値をセットしたらMDLのフローティングラベルが効かず、プレースホルダーと値が重なってしまった。
changeイベントかと思い強制発火させてみたものの解消せず、ちょっとはまった。
対応
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();
});
ちなみに https://codepen.io/anon/pen/ZWerBY のサンプルがとてもわかりやすかった。