<table id ="results_table">
<tr><th>Item Number</th><th>Item Price</th></tr>
</table>
<button onclick="addTableRow()">Add a new row</button>
const results_table= document.getElementById("results_table");
function addTableRow() {
var row = results_table.insertRow(-1); //add a new row to end of table. -1 means go to end of table
row.insertCell(0).innerHTML = "value"; //add new value to cell 1
row.insertCell(1).innerHTML = "value"; //add new value to cell 2
}
Extend the addTableRow Function by adding an additional column and inserting a button that will run a function.
function addTableRow() {
var row = results_table.insertRow(-1); //add a new row to end of table. -1 means go to end of table
row.insertCell(0).innerHTML = "value"; //add new value to cell 1
row.insertCell(1).innerHTML = "value"; //add new value to cell 2
<input type='button' value='Delete' onclick=\"deleteRow(this)\"> //add a button in the third column
}
We will add an argument to the function
function deleteRow(cellNumber) {
var i = cellNumber.parentNode.parentNode.rowIndex; //get the row number of the table
results_table.deleteRow(i); //go to the table and delete the specific row number i
}
Note: this will not delete data from an array that is being displayed in the table. If you wish to do this, you will need to include code to delete the relevant item or object from the array.
table_name.deleteRow(2); //delete this row number of table
Or if you created a const referencing the table at the top of your JS Note: -1 will delete the last row
table_name.deleteRow(-1); //delete last row of table
We need to know the row number and column (cell) number.
Refence the table location and use array access to update the value using innerHTML
table_name.rows[3].cells[2].innerHTML="value"
//This will edit LN3
This is how a html table organises and labels each cell
When designing your web app (for example, the one shown in the image on the right), consider all the page layout areas you will need to give an individual ID. Below is some sample code with a number of clearly defined areas labeled with IDs. Additionally, this application will input data into an object, which in turn is pushed to an array. This data is then displayed in a table.