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 = "";
});
}
