▲TOPへ戻る

【html】【javascript】セレクトボックスのoptionを自動生成し、今日現在の日付を初期設定する方法

以下のような、今日現在の日付が表示されるセレクトボックスをjavascriptで生成させる方法を紹介します。

まずはHTML。あとはjavascriptで生成します。

  <select name="year" id="year"></select>
  <select name="month" id="month"></select>
  <select name="day" id="day"></select>

表示させる要素と今日の日付をそれぞれ取得

  let year = document.getElementById("year");
  let month = document.getElementById("month");
  let day = document.getElementById("day");
  const date = new Date();
  const thisYear = date.getFullYear();

年のセレクトボックスのoptionを生成

  for (let i = 1930; i <= thisYear; i++) {
    let option = document.createElement("option");
    option.setAttribute("value", i);
    option.innerHTML = i + "年";
    year.appendChild(option);
    if (option.value == thisYear) {   //値が今年だったら
      option.setAttribute("selected", true);    // selectedの属性を付与
    }
  }

月のセレクトボックスのoptionを生成

  for (let i = 1; i <= 12; i++) {
    let option = document.createElement("option");
    option.setAttribute("value", i);
    option.innerHTML = i + "月";
    month.appendChild(option);
    if (option.value == date.getMonth() + 1) {  //値が今月だったら、「+1」 をお忘れなく
      option.setAttribute("selected", true);    // selectedの属性を付与
    }
  }  

日のセレクトボックスのoptionを生成

  for (let i = 1; i <= 31; i++) {
    let option = document.createElement("option");
    option.setAttribute("value", i);
    option.innerHTML = i + "日";
    day.appendChild(option);
    if (option.value == date.getDate()) {       //値が今日だったら
      option.setAttribute("selected", true);    // selectedの属性を付与
    }
  } 

完成したjavascriptのコード

  let year = document.getElementById("year");
  let month = document.getElementById("month");
  let day = document.getElementById("day");
  const date = new Date();
  const thisYear = date.getFullYear();

  for (let i = 1930; i <= thisYear; i++) {
    let option = document.createElement("option");
    option.setAttribute("value", i);
    option.innerHTML = i + "年";
    year.appendChild(option);
    if (option.value == thisYear) {
      option.setAttribute("selected", true);
    }
  }
  for (let i = 1; i <= 12; i++) {
    let option = document.createElement("option");
    option.setAttribute("value", i);
    option.innerHTML = i + "月";
    month.appendChild(option);
    if (option.value == date.getMonth() + 1) {
      option.setAttribute("selected", true);
    }
  }
  for (let i = 1; i <= 31; i++) {
    let option = document.createElement("option");
    option.setAttribute("value", i);
    option.innerHTML = i + "日";
    day.appendChild(option);
    if (option.value == date.getDate()) {
      option.setAttribute("selected", true);
    }
  }
point

createElement()で要素を作る

setAttribute()で属性「value」と「selected」を付与

appendChild()で要素の中に子要素を生成

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ