Creating an additional row in an HTML table is a common task, but it can become tricky when dealing with multiple forms and tables on one page. In my case, I have a form that contains only a table element, and I want to move some columns from the first row to a newly created row.
<h:form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</h:form>
The current output looks like: Item Info Description Product Keywords Documents Image Video
But I am aiming for something like this:
Item Info Description Product Keywords
NEW CELL1 Documents Image Video
This involves removing certain columns from the existing row and adding them to a new row. To achieve this, I've written a JavaScript function:
<script type="text/javascript">
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.getElementsByTagName("table")[0];
var tr = document.createElement("tr");
tr.id="row2";
table.appendChild(tr);
// Moving desired columns to the new row
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
var col5 = document.getElementById("col5");
tr.appendChild(col5);
var col6 = document.getElementById("col6");
tr.appendChild(col6);
var col7 = document.getElementById("col7");
tr.appendChild(col7);
}
</script>
My issue lies in dynamically generating the form since I can't assign IDs to elements. The script fails to find the table when using form.elements[0]
, as I need a more robust method to locate the table element for row creation.
I'm seeking a way to reliably target the table element to add a row within it.