LoginSignup
0
0

More than 1 year has passed since last update.

JavaScript 日時系input要素への初期値設定 簡易版

Last updated at Posted at 2022-12-20

日時系のinput要素に対し、現在日時に基づく初期値を設定するためのコードです。
過去に投稿した日時系のinput要素に対し現在日時に基づく値を初期値として設定ではvalueプロパティに入れる文字列を生成する方向で実装しましたが、使う機会も滅多に無さそうなtype=weekのためのiso8601週番号の計算も省きたい気がしたので、今回は別の方向で。

日時系のinput要素に対しては、valueAsNumberプロパティに対して適切な値を入れることでも設定が可能なので、これを利用してみます。

input_date_default_set.js
'use strict';
window.addEventListener('DOMContentLoaded', () => {
  const d = new Date();
  d.setMinutes(d.getMinutes() - d.getTimezoneOffset());

  document.querySelectorAll('input[data-now]').forEach(e => {
    if (e.value !== '' || !['time', 'date', 'week', 'datetime-local', 'month'].includes(e.type)) return;

    e.valueAsNumber = e.type === 'month' ?
      (d.getUTCFullYear() - 1970) * 12 + d.getUTCMonth() : Math.floor(d / 6e4) * 6e4;

    e.defaultValue = e.value;
  });
});

利用方法

現在日時を初期値として設定したい日時系のinputタグに、data-now属性を追記します。

example
<input type='time' data-now>

対応するtypeはtime date datetime-local month weekの5種です。
ブラウザが非対応のtypeであったり、value要素に既に何らかの値が入っている場合は何もしません。

元記事で対応していたtype=textに対してのテンプレート設定も今回は省いています。


設置デモ

example.html
<!DOCTYPE html>
<html lang='ja'>
<head>
    <meta name='viewport' content='width=device-width,initial-scale=1'>
    <meta charset='utf-8'>
    <title>日時系input要素に現在日時をデフォルト設定</title>
    <script src='input_date_default_set.js'></script>
</head>
<body>
<form>
    <!-- data-nowを追記で現在日時に基づく各typeに合った値を設定 -->
    time<br>
    <input type='time' data-now><hr>
    date<br>
    <input type='date' data-now><hr>
    datetime-local<br>
    <input type='datetime-local' data-now><hr>
    month<br>
    <input type='month' data-now><hr>
    week<br>
    <input type='week' data-now><hr>
<input type='reset'>
</form>
</body>
</html>

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