I'm a hobby coder and struggle with following issue: I got a table element with a few rows, each row 3 cells. Via a button at the bottom I would like to add rows. The table looks like this:
<table id="mytable">
<tr id="line[0]"><td id="cellA[0]"</td><td id="cellB[0]"</td><td id="cellC[0]"</td></tr>
<tr id="line[1]"><td id="cellA[1]"</td><td id="cellB[1]"</td><td id="cellC[1]"</td></tr>
<tr id="line[2]"><td id="cellA[2]"</td><td id="cellB[2]"</td><td id="cellC[2]"</td></tr>
</table>
I loop through with elementbyID "line" to find that the last line is [2]. And then add a new line like this:
var table = document.getElementById("mytable");
var row = table.insertRow(oldID 1);
row.setAttribute("id","line[" oldID 1 "]");
This works great.
Next I get the content of the last line via var lastLine = document.getElementById(oldID).innerHTML. Now since the td IDs are cellA[2], cellB[2] and cellC[2]. I would like to replace those with [3].
I tried following:
var oldVar = "[" oldID "]";
var newVar = "[" oldID 1 "]";
var regex = new RegExp(oldVar, "g");
var neueLine = lastLine.replace(regex, newVar);
but this results in ids like this "cellA[3][3]", "cellB[3][3]" and "cellC[3][3]".
I feel like my limited knowledge is missing out on the supposed way to do this.
Thanks a lot for your help!
CodePudding user response:
You can use replaceAll
lastLine = lastLine.replaceAll("[" oldID "]","[" (oldID 1) "]")
CodePudding user response:
This will work - it can possibly be coded in less instructions but is very readable. Also I fixed the invalid HTML
window.addEventListener("load", function() {
const table = document.querySelector("#mytable tbody");
document.getElementById("add").addEventListener("click", function() {
const lastRow = table.querySelector("tr:last-child")
let id = lastRow.id.replace(/\D /g, ""); // grab and convert to number
let newId = id 1;
const newLine = lastRow.cloneNode(true);
newLine.id = newLine.id.replace(id,newId);
newLine.querySelectorAll("td").forEach(cell => cell.id = cell.id.replace(id,newId))
table.appendChild(newLine)
})
})
<input type="button" id="add" value="Add" />
<table id="mytable">
<tbody>
<tr id="line[0]">
<td id="cellA[0]">A</td>
<td id="cellB[0]">B </td>
<td id="cellC[0]">C</td>
</tr>
<tr id="line[1]">
<td id="cellA[1]">A </td>
<td id="cellB[1]">B</td>
<td id="cellC[1]">C </td>
</tr>
<tr id="line[2]">
<td id="cellA[2]">A</td>
<td id="cellB[2]">B</td>
<td id="cellC[2]">C</td>
</tr>
</tbody>
</table>