0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

行追加、行削除、クリアボタン

Posted at

3. 行追加・行削除ボタン

ボタン押下後↓

  <button onclick="addRow()">行を追加</button>
  <button onclick="deleteRow()">行を削除</button>
  
  <script>
    function addRow() {
      const table = document.getElementById("sampleTable").getElementsByTagName("tbody")[0];
      const currentRows = table.querySelectorAll("tr").length;
      const newNo = currentRows / 5 + 1;

      // 上段1行目(No, 項目名, 備考付き)
      const mainRow = table.insertRow();
      mainRow.insertCell().outerHTML = `<td rowspan="5">${newNo}</td>`;
      mainRow.insertCell().outerHTML = `<td rowspan="5">データ${String.fromCharCode(64 + newNo)}</td>`;
      mainRow.insertCell().outerHTML = `<td colspan="5">値1</td>`;
      mainRow.insertCell().outerHTML = `<td rowspan="5">コメント${newNo}</td>`;

      // 下段4行(単独セル)
      for (let i = 0; i < 4; i++) {
        const subRow = table.insertRow();
        const cell = subRow.insertCell();
        cell.textContent = "値3";
      }
    }

    function deleteRow() {
      const table = document.getElementById("sampleTable").getElementsByTagName("tbody")[0];
      const totalRows = table.querySelectorAll("tr").length;
      if (totalRows <= 5) {
        alert("これ以上削除できません。");
        return;
      }
      // 下から5行分削除
      for (let i = 0; i < 5; i++) {
        table.deleteRow(-1);
      }
    }
  </script>

4. クリアボタン

途中
// クリア(データ内容のみ削除)
<button onclick="clearBtn">クリア</button>

    function clearBtn() {
      const tbody = document.querySelector("#sampleTable tbody");
      const cells = tbody.querySelectorAll("td");
      cells.forEach(cell => {
        cell.textContent = "";
      });
    }
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?