エンジニアのひよこ_level10

毎日更新してた人。たまに記事書きます。

【JavaScript】テーブルの列をテンプレートに沿ってボタンで追加する【888日目】

テーブルのカラムを追加したい

テーブルの入力項目をどんどん増やしたい。

増やすとすると、その入力項目のテンプレートが必要。

テンプレートに合わせて、テーブルの列を増やしていくスクリプトを書きたい。

ボタンを押すと増やすプログラム

f:id:willow710kut:20200319220112g:plain

// 非表示にしておいたテンプレートを元に、要素を追加して表示する
function addTableTr(target_tbody_selector, target_template_selector) {
    $(target_tbody_selector).append($(target_template_selector).html());
}
<table>
  <thead>
    <th>名前</th>
    <th>色</th>
  </thead>
  <tbody id="t-body">
  </tbody>
  <tbody class="hidden" id="t-template">
    <td><input type="text"></td>
    <td><input type="text"></td>
  </tbody>
</table>

<button type="button" onclick="addTableTr('#t-body', '#t-template')">列を増やす</button>
  1. テンプレートを非表示で用意する
  2. 増やすターゲットとテンプレートのidを指定する
  3. テンプレート内のhtmlを、ターゲットに加える

という仕組み。

テンプレートの中身を帰れるので、用途に合わせて変えていただくと、良いと思います。

例(codepen)

https://codepen.io/klack710/pen/qBdyEMd?editors=1111