Add new row at each HTML page load with Javascript [duplicate] - javascript

This question already has answers here:
How to make changes to HTML document permanent using Javascript?
(3 answers)
Closed 3 years ago.
I've got a really basic HTML page that simply displays a table. I'm trying the below code so that I can add a new row to the bottom of the table each time the page is loaded (even if it's the same data for now). However, each time I load the page, the bottom element keeps getting overridden with the same data. I am trying to do something like this example on W3 Schools (without the button, but the same concept).
My code is as follows:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="table" style="width:70%; text-align: center;">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Row</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
<script>
function myFunction() {
var table = document.getElementById("table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
};
myFunction();
</script>
</body>
</html>
I've also tried replacing myFunction above with document.addEventListener("DOMContentLoaded", function(){...}, but that hasn't solved my issue either.

JavaScript will not make permanent changes in your HTML files.
This means that after you load the page, your HTML code will be displayed and then the function will be executed, adding a new row.
After you reload again, the same process will happen, and the row will be added after the end of your second HTML row.
It doesn't matter whether you use the simple method on your code or the other one you suggest (with document.addEventListener), this function is bound to be executed only once and will not add more than one row.

The issue is that your page isn't storing its data anywhere, so whenever you reload the page you're basically destroying any data you've modified and loading it from scratch again. You should use localStorage or a local database or something like that to keep track of data, and save your page's state when the function is called or on page unload.
In pseudocode:
const loadFromLocalStorage = () => {
const rows = localStorage.getItem("extra_rows") // extra_rows can be an array
for(elem in rows) {
// add to table
}
}
const saveToLocalStorage = (obj) => {
const rows = localStorage.getItem("extra_rows")
localStorage.setItem([...rows, obj])
}
const addNewRow = () => {
var table = document.getElementById("table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
const obj = {
cell1: cell1, cell2: cell2, cell3: cell3
}
saveToLocalStorage(obj)
}
const myFunction = () => {
loadFromLocalStorage()
addNewRow()
}
myFunction()

Related

Creating a hyperlink within a table cell

I'm attempting to creating a hyperlink within a cell of a table, but currently the hyperlink just displays as text within the table. Looking at the console I can see linkElement is getting created properly as:
text
My JS code
//Creating the table
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
//creating URL elements
linkElement = document.createElement("a");
linkElement.setAttribute("href", url);
var linkText = document.createTextNode(url);
linkElement.append(linkText);
console.log(linkElement)
cell1.innerHTML = linkElement;
cell2.innerHTML = appVersion;
My HTML:
<table id="myTable">
</table>
Use cell1.append(linkElement), cell1.innerHTML is meant to be use when providing the HTML as string not an object.
Figured it out using cell1.innerHTML= ''+linkElement+'';

Trouble with setting id for dynamically generated table

Never mind. This was my mistake. This code works fine.
I have a function that's supposed to create and populate a table. I'm also trying to set the id element of some of the columns, but the function that I have isn't working and I can't seem to figure out why.
This is my code:
HTML:
<div id="result_table">
<table border="0" cellspacing="3" cellpadding="3" id="summaryTable" class="tablesorter table table-striped">
<thead>
<tr style="font-weight: bold; text-align: center;">
<th>Well ID</th>
<th>Dominant Gene</th>
<th>%</th>
<th>Secondary Gene</th>
<th>%</th>
<th>No. of Reads that Mapped</th>
<th>No. of Mutations</th>
<th>Mutation Information</th>
<th>View</th>
</tr>
</thead>
<tbody id="summaryBody">
</tbody>
</table>
</div>
Javascript:
function structureTable(test){
if (kiloseqResult==null){
throw "Error: no databse defined"
};
document.getElementById("summaryTable").style.visibility="visible";
kiloseqDatabase = JSON.parse(kiloseqResult);
var table = document.getElementById("summaryBody");
for (i=0;i<kiloseqDatabase.length;i++){
var row = table.insertRow(i);
var kiloseqKeys = Object.keys(kiloseqDatabase[i])
var keyLength = Object.keys(kiloseqDatabase[i]).length;
// Painstakingly setting up the cells...
var cell = row.insertCell(0);
cell.innerHTML = kiloseqDatabase[i]['id']
var cell = row.insertCell(1);
cell.innerHTML = kiloseqDatabase[i]['gene1'].substr(5)
var cell = row.insertCell(2);
cell.innerHTML = parseFloat(kiloseqDatabase[i]['percent1']).toFixed(2)
var cell = row.insertCell(3);
if (kiloseqDatabase[i]['gene2']=="None"){
cell.innerHTML = "None"
} else {
cell.innerHTML = kiloseqDatabase[i]['gene2'].substr(5)
}
var cell = row.insertCell(4);
cell.innerHTML = parseFloat(kiloseqDatabase[i]['percent2']).toFixed(2)
var cell = row.insertCell(5);
cell.innerHTML = kiloseqDatabase[i]['count']
var cell = row.insertCell(6);
cell.innerHTML = ""
var cell = row.insertCell(7);
cell.innerHTML = ""
var cell = row.insertCell(8);
cell.innerHTML = ""
};
$(document).ready(function()
{
$("#summaryTable").tablesorter(
{sortList: [[0,0], [1,0]]}
);
}
);
for (i=0;i<kiloseqDatabase.length;i++){
document.getElementById("summaryBody").rows[i].cells[6].id = "test";
};
};
kiloseqResult is a variable that checks whether kiloseqDatabase is populated. kiloseqDatabase contains the information that's supposed to populate the table.
Oddly enough, the for-loop that sets up the ID (and yes, I did try including this in the first for-loop but tried breaking it up when that didn't work) is fine when I run it in my Chrome's console. But it doesn't seem to work within the function.
Any help would be much appreciated. Thank you!
Have you tried putting your ID assignment logic within the document.ready scope? You can't assign an ID to an element or select it from the DOM before it's rendered:
$(document).ready(function()
{
$("#summaryTable").tablesorter(
{sortList: [[0,0], [1,0]]}
);
for (i=0;i<kiloseqDatabase.length;i++){
document.getElementById("summaryBody").rows[i].cells[6].id = "test";
};
}
);

How to access the contents of a cell in HTML table using the cell id?

I have created a table in HTML using JavaScript functions insertRow() and insertCell() functions. I have assigned an id for each cell. I would like to get the value/content of the cell in JavaScript.
Following is the code used to create the table:
<HTML>
<HEAD>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.id = rowCount;
var cell1 = row.insertCell(0);
cell1.id = rowCount + 'a';
cell1.innerHTML = "CELL1";
var cell2 = row.insertCell(1);
cell2.id = rowCount + 'b';
cell2.innerHTML = "CELL2";
var cell3 = row.insertCell(2);
cell3.id = rowCount + 'c';
cell3.innerHTML = "CELL3";
var cell4 = row.insertCell(3);
cell4.id = rowCount + 'd';
cell4.innerHTML = "CELL4";
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<thead>
<TD>Column 1</TD>
<TD>Column 2</TD>
<TD>Column 3</TD>
<TD>Column 4</TD>
</thead>
</TABLE>
</BODY>
I have already tried out the following options:
alert(document.getElementById(1a));
Null
alert(document.getElementById(1a).value);
Error message: Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined
alert(document.getElementById("dataTable").rows[rowCount].cells[0]);
[Object]
alert(document.getElementById("dataTable").rows[rowCount].cells[0].toString());
[Object]
alert(document.getElementById("dataTable").rows[rowCount].cells[0].value);
undefined
Here's an example of how you get the cell's value.
Given you name them serially (starting with row then a,b,c,d you should be able to access them by id as 1a or 3c. With that said, the following is working (supplemental to what you've posted):
<!-- head -->
<script>
function getVal(cellId){
var cell = document.getElementById(cellId);
document.getElementById('a').innerHTML = cell.innerHTML;
// highlight the cell for visual effect
cell.className = 'target';
setTimeout(function(){ cell.className = ''; }, 1e3);
}
</script>
<!-- /head -->
<!-- body -->
<INPUT type="text" id="q" />
<INPUT type="button" value="Get Value" onclick="getVal(document.getElementById('q').value);" />
<span id="a"></span>
<!-- /body -->
Firstly, you should know the row number.
Use document.getElementById(id) to get the content. For example, id = $rownumber + [abcd]
Table cells have no value attribute, but you can access the content via the innerHTML property or the innerText property. The differences are that the latter has somewhat more limited browser support and it gives the text content, without any tags. Example:
alert(document.getElementById('1a').innerHTML)
If this does not work (as a comment seems to say), then the problem is somewhere else. Then you should post code that actually reproduces the issue.
To access the contents of the cells with your current code you only have to address each cell by the id you gave it, then access the innerHTML atribute:
var myCell = document.getElementById('1c')
var myCellContent = myCell.innerHTML
Remember that you have the heading for each column, so your first row that actually has content will be the '1' and not the '0'.
I am able to access the cell contents using the following piece of code:
document.getElementById("dataTable").rows[rowCount].cells[0].innerHTML

How to save JavaScript generated content as HTML in the file?

I have a table with 1 row, 11 columns. Now I generated the following JavaScript code to add a new row using a Button.
The issue is, when i refresh the page, the new rows that i added using this javascript, are lost. I want them to be saved permanently in the HTML file. How can this be done?
<script>
function AddNewRow()
{
var table = document.getElementById("table1");
var row = table.insertRow(1);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
var cell8 = row.insertCell(8);
var cell9 = row.insertCell(9);
var cell10 = row.insertCell(10);
</script>
The HTML file remains on a server inaccessible to the client, but it would be perfectly possible for the browser to save the added information - either in HTML form, or as a more storage-focused format like XML/JSON. It would then need to be loaded back into Javascript and re-added to the page each time your page starts up.
Read up on the localStorage documentation at Mozilla - they could give you a general idea of storing/loading. With the innerHTML readable/writable property, hopefully you have an idea of how you could accomplish this.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage

Dynamics table creator Or <td> <tr> creator

If i have a table with 5 rows and 4 column.but i have to add values on the next row.there is no database related dependency.I have ADD button and i want to code it like when ever i will click on ADD button there is aaddition of new row.......
I mean the creaton of Rows in the table willbe dynamically...
Can ayy one sho me any sample code /Link on
http://jsfiddle.net/ or just give me any Url that contains the demo code for that
See this tutorial. It show how to add new row and column.
I don't know how to do on jsFiddle but made one demo on my machine and is as follows:
<html>
<head>
<title>Demo</title>
<script>
function appendRow(tblId)
{
var tbl = document.getElementById(tblId);
var newRow = tbl.insertRow(tbl.rows.length);
var newCell = newRow.insertCell(0);
newCell.innerHTML = 'Hello World!';
}
</script>
</head>
<body>
<table id="tabl" border="1">
<tr>
<td>Old one</td>
</tr>
</table>
<input type="button" value="AddRow" onClick="appendRow('tabl')">
</body>
It might be help full JQuery add row in to table
Here you go:
http://jsfiddle.net/dgMET/1/
var table = document.getElementById("table");
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(0);

Categories