How to assign variable ids to tables rows and columns - javascript

How can I assign ids to the rows, columns if I want to use this method for creating tables. Knowing that the ids are variables, eg. array length.
function addRow(tableID, text) {
// Get a reference to the table
var tableRef = document.getElementById(tableID);
// Insert a row in the table
var newRow = tableRef.insertRow();
// Insert a cell in the row
var newCell = newRow.insertCell();
// Append a text node to the cell
var newText = document.createTextNode(text);
newCell.appendChild(newText);
}
// Call addRow(text) with the ID of a table
addRow('TableA', 'Brand new row');
addRow('TableA', 'Another new row');

Let us say you want to add k rows. Simple, create the rows in a loop of k iteration.
var tableRef = document.getElementById(tableID);
//to add k rows
for (x=0; x<k; x++)
{
// Insert a row in the table
var newRow = tableRef.insertRow(x);
newRow.setAttribute("id","row"+x);
// Insert a cell in the row
var newCell = newRow.insertCell(0);
// Insert another cell in the row
var newCell2 = newRow.insertCell(1);
//insert HTML text in the cells
newCell.innerHTML="text1";
newCell2.innerHTML="text2";
} //end for
}//end function

Related

HTML dynamic table row is not getting dynamic id

I have a dynamic HTML table that makes a new row when there is a new user being registered. Now i am trying to give the row a id with a for loop but they al get the same id which is: tableID99. Here's my code:
for (var i = 0; i < 100; i++) {
row.id = "tableID" + i
}
It looks like the table does not know it is dynamic or something. When i console.log(row.id) it is an ascending list with tableID1 -> tableID1 -> tableID2 etc.
What am i missing here?
Edit:
function showTable() {
// dummy data to start with
let localStorageData = JSON.parse(localStorage.getItem("users"))
// get button and table with query selector
let createTable = document.querySelector("#table")
// table heading
let headers = ["ID", "Gebruikersnaam", "Email", "Wachtwoord", "Gebruikersrol", "Voornaam", "Achternaam", "Geboortedatum", "Adres", "Huisnummer", "Postcode", "Plaatsnaam", "Land", "Suspended"]
// create table elements
let table = document.createElement("table");
let headerRow = document.createElement("tr");
// start loop
headers.forEach(headerText => {
// create table heading and textnode
let header = document.createElement("th");
let textNode = document.createTextNode(headerText);
// append to DOM
header.appendChild(textNode);
headerRow.appendChild(header);
table.appendChild(headerRow)
});
// create loop that makes table
localStorageData.forEach(localStorageData => {
blokkeerButtons()
// create table row
let row = document.createElement("tr");
// create loop that set data in cells
Object.values(localStorageData).forEach(localStorageData => {
// create element and textnode
let cell = document.createElement("td");
let textNode = document.createTextNode(localStorageData as string);
// append to DOM
cell.appendChild(textNode);
row.appendChild(cell);
for (var i = 0; i < 100; i++) {
row.id = "tableID" + i
console.log(row.id)
}
});
// append to DOM
table.appendChild(row);
});
// append to DOM
createTable.appendChild(table);
}
It looks like you have 3 loops in your code to create the table: localStorateData.foreach, Object.values(localStorageData).forEach, and that for loop that counts from 0 to 99.
You are making exactly one new row in the outermost loop. In that innermost for loop, all you're doing is resetting the id of that one new row 100 times.
Consider changing to something like this:
// create loop that makes table
var rowCount = 0;
localStorageData.forEach(localStorageData => {
blokkeerButtons()
// create table row
let row = document.createElement("tr");
// create loop that set data in cells
Object.values(localStorageData).forEach(localStorageData => {
// create element and textnode
let cell = document.createElement("td");
let textNode = document.createTextNode(localStorageData as string);
// append to DOM
cell.appendChild(textNode);
row.appendChild(cell);
});
// append to DOM
row.id = "tableID" + rowCount;
rowCount++;
table.appendChild(row);
});

Way to add href in row data in table using html

Is there a way to display a table that with rows that will include its value in the hyperlink?
ReferenceNumber
1234 -> this one is clickable leading to localhost:8080/getDetails/1234
1235
Thank you
//Add the data rows from Excel file.
for (var i = 0; i < excelRows.length; i++) {
//Add the data row.
var row = table.insertRow(-1);
//Add the data cells.
var cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].ReferenceNumber;
}
Just wrap it in <a></a> tag.
//Add the data rows from Excel file.
for (var i = 0; i < excelRows.length; i++) {
//Add the data row.
var row = table.insertRow(-1);
//Add the data cells.
var cell = row.insertCell(-1);
var link = '' + excelRows[i].ReferenceNumber + '';
cell.innerHTML = link;
}

Add links to all cells in column of html table

I would like to loop through the cells in the second column of an html table, adding a link to the text in each cell. I have a generic base URL, with a hash that should be defined by an integer in the corresponding cell in the first column of the table.
For example, the text in first cell of the second column should link to:
http://test.example.com/foo.html#1
Where the #1 is defined by the integer in the first cell of the first column (1). Then repeat for each row, where the integer in each cell of the first column should be used for the hash.
Pure js or jquery would work. I have found this snippet of jquery, which seems like a good start for iterating through each cell in the second column:
$('#table1 td:nth-child(2)').each(function(elem) {
//do something with elem
});
Is this jquery method appropriate, and if so, how can I apply the links as described?
As a possible alternative, could I modify the function I use to create the table?:
function createTable(tableData) {
var table = document.getElementById('table1');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.getElementById('wrapper').appendChild(table);
}
createTable(table_input);
Since you are the one creating the table at the first place it is best to modify the code and render it correctly (as oppose to updating it later on client-side).
Based on your comments and clarification here is the updated code, storing the integer value of first column of each row to use it as url on second column:
function createTable(tableData) {
var table = document.getElementById('table1');
var tableBody = document.createElement('tbody');
var theUrl = 'http://test.example.com/foo.html#'; //replace with real URL
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
var i = 1;
var numValue = '';
var content = '';
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
numValue = (i==1) ? cellData : numValue ;
if(i==2){
content = document.createElement('a');
content.setAttribute('href', theUrl + numValue);
content.innerText = cellData ;
}
else{
content = document.createTextNode(cellData);
}
cell.appendChild(content);
row.appendChild(cell);
i++;
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.getElementById('wrapper').appendChild(table);
}
createTable(table_input);
You may change the following code:
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
to
for (var i=0; i<rowData.length;i++)
{
var cell = document.createElement('td');
if (i==1)
{
var link=document.createElement("a");
link.href="http://test.example.com/foo.html#"+(i+1);
link.text=rowData[i];
cell.appendChild(link);
}
else
cell.textContent=rowData[i];
row.appendChild(cell);
}

Fetching user input from input field into js table that creates table cells via for loop

I've been attempting to fetch user input value from input fields to later on set it into a summary table that creates cells using javascript but can't seem to get it to work.
Following is my code:
function summonTable(f) {
var sLoc = f.countryf.value();
var eLoc = f.countryt.value();
var sDate = f.sdate.value();
var eDate = f.edate.value();
var div = document.getElementById("summary");
var magicTable = document.getElementById('summaryTable').querySelectorAll('tbody tr'),
var row = document.createElement('tr');
var th = document.createElement('th');
th.textContent = sDate;
var td = document.createElement('td');
td.textContent = sLoc;
//To state which row and column this cell goes to.
row.appendChild(th);
div.appendChild(magicTable);
});
The function summonTable will take in the arguement form f that contains the input fields, I've tried basic textboxes, checkboxes, radios, but all to no avail. The variables sLoc, eLoc are basically texts for countries and sDate, eDate are supposed to be dates.
function summonTable(f) {
var sLoc = f.countryf.value();
var eLoc = f.countryt.value();
var sDate = f.sdate.value();
var eDate = f.edate.value();
var div = document.getElementById("summary");
// to get the last row of the table
var magicTable = document.getElementById('summaryTable').querySelectorAll('tbody tr:last-child'),
var row = document.createElement('tr');
var th = document.createElement('th');
th.textContent = sDate;
var td = document.createElement('td');
td.textContent = sLoc;
//To state which row and column this cell goes to.
row.appendChild(th);
magicTable.after(row); //To add the row after the last row
div.appendChild(magicTable);
});

Get value from input in a table

I have the following code:
function create_row() {
var table = document.getElementById("main_table");
var n = table.rows.length;
var m = table.rows[0].cells.length;
var row = table.insertRow(-1);
var cell = row.insertCell(0);
cell.innerHTML = n;
var cell = row.insertCell(1);
cell.innerHTML = "<input size=10>";
for (i=2; i<m; i++) {
var cell = row.insertCell(i);
cell.innerHTML = "<input size=4>";
}
}
function print_values() {
var table = document.getElementById("main_table");
for (i=1; i<table.rows.length; i++) {
console.log(table.rows[i].cells[1].innerHTML);
}
}
However, when I print values I get <input size="10">.
The problem is that when I create a row, I add manually some value to a table (in a webpage) and I want to print those values in a log. How can I access those values, but not html of the input?
I probably can assign an id to each input form and then access value keyword, but thought maybe it could suffice using table cells.
The input element is a child of the table cell. And you have to use .value to get the value of an input, not .innerHTML.
console.log(table.rows[i].cells[1].childNodes[0].value)
You want the insides of your input, so you'll have to select that input.
yourExistingSelector.querySelector("input").innerHTML
In your case:
table.rows[i].cells[1].querySelector("input").innerHTML

Categories