JSで0補完

formで入力したときに、最大入力数までpadStart()によって0で埋めるやり方。

下はinputに対して、

フォーカスしたときに

  • 背景色を変える
  • 入力値を空にする
  • プレースホルダーでデフォルト値を表示する

フォーカスが外れたら

  • 背景色を消す
  • プレースホルダーを消す
  • 何も入力されていなかったらデフォルト値を入力
  • 入力されているが、inputの最大入力値より短かったら0で埋める

をしています。

$(function () {
    $('form input')
        .focusin(function (e) {
            $(this).css('background-color', '#f8f8f8');
            $(this).val("");
            $(this).attr("placeholder", $(this).attr("value"));
        })
        .focusout(function (e) {
            $(this).css('background-color', '');
            $(this).attr("placeholder", '');
            var input = $(this).val();
            if (!input) {
                var defa = $(this).attr("value");
                $(this).val(defa);
            } else if (input.length < $(this).attr("maxlength")) {
                var padNum = String(input).padStart($(this).attr("maxlength"), '0');
                $(this).val(padNum);
            }
        });
});

参考