LoginSignup
1
1

More than 1 year has passed since last update.

【javascript】動的なtable生成、tdに動的なselectを生成

Last updated at Posted at 2021-06-09

やりたいこと

tableの行を動的に追加。
さらにoptionも配列から動的に追加

想定

配列はDBから取得。DBが変われば、option選択肢も動的に変更されるようにする

※本当はjqueryを使ったほうがみやすくすっきりしますが、あえてjavascriptで書きます。
 jqueryでの記述バージョンもそのうちアウトプットしようと思います。

下記をもっとシンプルに分解した記事

【javascript】シンプルな動的selectの生成、option(選択肢)の追加
【javascript】シンプルなtableの動的行追加・削除(ボタンクリックで行追加・削除)
【javascript】シンプルな動的tableのinputの値取得

完成形、動作確認(ここでは配列をあらかじめ設定)

See the Pen js table td→input by Hirofumi Sato (@hfmst) on CodePen.

コード

下記、データ取得については別途投稿します。

index.html
<div>
  <button onclick="addrow()">行追加</button>
  <button onclick="getdt">送信</button>
  <button onclick="getdt">取得</button>
</div>
<table border="1" id="tbl">
  <tr>
    <th>日付</th>
    <th>担当</th>
    <th>タスク</th>
  </tr>
</table>
js.html
function addrow(){

  let tbl = document.getElementById('tbl');

  let name=["山田太郎","斎藤花子","最上祐樹"];
  let todo=["メール対応","会議","資料作成","掃除"];

//input type=dateをtrに追加
  let tr = document.createElement('tr');
  let datetd = document.createElement('td');
  let dateinp = document.createElement('input');
  //↑上記で必要な要素(tr,td,input)を用意

  dateinp.setAttribute('type','date');//inputを日付形式に
  datetd.appendChild(dateinp);        //tdに追加
  tr.appendChild(datetd);               

//下記、createSelect関数に、配列、tr、tblを渡す
  createSelect(name,tr,tbl);
  createSelect(todo,tr,tbl);

  tbl.appendChild(tr);

}

//担当とタスクは同じくselectなので、createSelectを使いまわします。
function createSelect(arr,tr,tbl){

  let sl = document.createElement('select');
  let td = document.createElement('td');
  for(let num in arr){        //引数で受け取ったからoptionを作って動的にselect生成
    let op = document.createElement('option');
    op.text = arr[num];
    sl.appendChild(op);
  }
  td.appendChild(sl);
  tr.appendChild(td);

}

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