My doubt is quite confusing. I'll break it down as simple as possible.
In HTML page I have a table inside a forEach loop. So multiple tables will occur. But all the tables has same header but rest of the values are different. So I need to set the table header in JavaScript to reduce the HTML code.
function myFunction()
{
var table = document.getElementById("myTable");
var header = table.createTHead();
var row = header.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "<b>Resource Name</b>";
}
This is the code I have used. But id doesn't repeat again. So the table header is only coming for first table.
Any solutions or alternatives for id ?
var tables = document.getElementsByTagName("table");
var len = tables.length, i=0, header, row, cell;
for(;i<len;i++){
header = tables[i].createTHead();
row = header.insertRow(0);
cell = row.insertCell(0);
cell.innerHTML = "<b>Resource Name</b>";
}
http://fiddle.jshell.net/4AmmP/1/
Edit (Using class)
Add class to the tables you want to get affected (say class="myTableClass") and use the below edited code
var tables = document.getElementsByTagName("table");
var len = tables.length, i=0, header, row, cell;
for(;i<len;i++){
/* Check if the table has the class "myTable" */
if(tables[i].className === "myTable") {
header = tables[i].createTHead();
row = header.insertRow(0);
cell = row.insertCell(0);
cell.innerHTML = "<b>Resource Name</b>";
}
}
http://fiddle.jshell.net/4AmmP/2/
Related
(first off, I'm very new to JavaScript - HTML/PHP I know a little better)
I would like to send the table data (which is dynamically created by javascript - depending on how many students there are in the database) to a PHP file to process. The table is created and added to HTML-id "create_groups" (which is included in a HTML Form) after the button "Create Groups" has been pressed.
I've tried giving each table row it's own name (tr.setAttribute('name', students[i][col[0]]);) which works (at least the browser shows it in the "console" window) but when I press "submit" the Javascript table data isn't transmitted to the create_groups.php. At least I can't seem to get hold of it.
teacher.php
function createTableFromJSON() {
hideAll();
document.getElementById('create_groups').style.display = "block";
let con = new XMLHttpRequest(); //Create Object
console.log("1");
con.open("GET", "teacher_check.php", true); //open the connection
con.onreadystatechange = function() { //define Callback function
if (con.readyState == 4 && con.status == 200) {
console.log("2");
console.log(this.responseText);
let response = this.responseText;
let students = JSON.parse(this.responseText);
//Convert String back into JSON object
console.log(students);
let col = [];
for (let key in students[0]) {
col.push(key);
}
// CREATE DYNAMIC TABLE.
let table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
let tr = table.insertRow(-1); // TABLE ROW AT THE END
let th = document.createElement("th");
th.innerHTML = "SELECT";
tr.appendChild(th);
for (let i = 0; i < col.length; i++) {
let th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (let i = 0; i < students.length; i++) {
tr = table.insertRow(-1);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
console.log(students[i][col[0]]);
//this shows the right names
tr.appendChild(checkbox);
tr.setAttribute('name', students[i][col[0]]);
for (let j = 0; j < col.length; j++) {
let tabCell = tr.insertCell(-1);
tabCell.innerHTML = students[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
let divContainer = document.getElementById("create_groups");
//divContainer.innerHTML = "";
divContainer.appendChild(table);
document.getElementById("create_groups").submit();
}
}
con.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //Set appropriate request Header
con.send(); //Request File Content
}
function hideAll() {
document.getElementById('create_groups').style.display = "none";
}
<input type="button" name="create_groups" value="Create Groups" onclick="createTableFromJSON()">
<form action="create_groups.php" method ="post">
<div class="container white darken-4" id="create_groups" style="display:none;">
<p>
<label>
<span>Groupname:</span>
<input type="text" name="groupname">
</label>
</p>
<p><button type="submit" name ="submit">Submit</button></p>
</div>
create_groups.php
if (isset($_POST['submit'])) {
$student = $_POST['stud'];
$groupname = $_POST['groupname'];
echo $groupname;
echo $student;
}
I expect to be able to access all the names of the students in the create_groups.php file, which are checked off in the other teacher.php file in the table. Obviously the "isChecked" part isn't implemented yet, because the other part doesn't work yet.
So the creating of the table with the correct data works, just not the transmitting to the PHP file.
There is few issues in html syntax and javascript as well please try correcting them.
hideAll() function definition is missing in you script first line.
Second in html before tag there is unnecessary ">" character.
(This is my first question here and I am new to programming)
I am stuck on a problem and I tried to take something from here:
http://jsfiddle.net/4pEJB/
Dynamically generated table - using an array to fill in TD values
The function I created receive two vectors and creates a table with 2 columns, one for each vector, and lines = vector.length.
The function works fine, it seems to create the table as I need, but it doesn't show the table created on the browser screen after button click. By using some 'alert()' on the for loops I was able to verify that it uses the correct data.
In fact, when the button is clicked, it calls another function that processes some data and passes two vectors on this function I am showing here, but this part works well.
Here is the HTML part:
<div class="tableDiv">
<input type="button" onclick="createtable([1,3,5,7,9],[2,4,6,8,10])" value="Show data">
</div>
And here is the JavaScript part:
function createtable(vet_1,vet_2){
var tableDiv = document.getElementById("tableDiv");
var table = document.createElement("table");
var tableBody = document.createElement('tbody');
for (var r=0;r<vet_1.length;r++){
var row = document.createElement("tr");
for (var c=0;c<2;c++){
var cell = document.createElement("td");
if (c==0){cell.appendChild(document.createTextNode(vet_1[r]));}
else if(c==1){cell.appendChild(document.createTextNode(vet_2[r]));}
row.appendChild(cell);
}
tableBody.appendChild(row);
}
tableDiv.appendChild(table);
}
When the function finishes the table feed, it stops on tableDiv.appendChild(table);
Any advice or suggestions will be greatly appreciated! (I speak portuguese, I am sorry for some errors)
EDIT: it's possible to avoid the increment on the number of table rows that occurs every time we click the button (the solution provided generates one new table under the previous table). To solve this, I just added this line on the beggining of the function code (need to put the button outside the div and let the div empty, otherwise it will hide the button):
document.getElementById("tableDiv").innerHTML = "";
you are capturing by id, but you set up a class.chang it to id
<div id="tableDiv">
and append the tableBody into table.You're populating the table body with rows, but never appended the body into the table element.
function createtable(vet_1,vet_2){
var tableDiv = document.getElementById("tableDiv");
var table = document.createElement("table");
var tableBody = document.createElement('tbody');
for (var r=0;r<vet_1.length;r++){
var row = document.createElement("tr");
for (var c=0;c<2;c++){
var cell = document.createElement("td");
if (c==0){cell.appendChild(document.createTextNode(vet_1[r]));}
else if(c==1){cell.appendChild(document.createTextNode(vet_2[r]));}
row.appendChild(cell);
}
tableBody.appendChild(row);
}
table.appendChild(tableBody) // append tableBody into the table element
tableDiv.appendChild(table);
}
<div id="tableDiv">
<input type="button" onclick="createtable([1,3,5,7,9],[2,4,6,8,10])" value="Show data">
</div>
You try to append the var table to the tableDiv but the var table is stil empty.
Before append the tableBody to the var table and it will work.
Use id instead of class in your HTML Markup
<div id="tableDiv">
and then use the following code.
function createtable(vet_1,vet_2){
var tableDiv = document.getElementById("tableDiv");
var table = document.createElement("table");
var tableBody = document.createElement('tbody');
for (var r=0;r<vet_1.length;r++){
var row = document.createElement("tr");
for (var c=0;c<2;c++){
var cell = document.createElement("td");
if (c==0){cell.appendChild(document.createTextNode(vet_1[r]));}
else if(c==1){cell.appendChild(document.createTextNode(vet_2[r]));}
row.appendChild(cell);
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
tableDiv.appendChild(table);
}
First you are accessing the div using id whereas the node is defined with a class.
Secondly, you have to append the body to the table node first, and then append the table to the div selected.
Try this code snippet to move on.
I am creating a program that connects to Firebase Realtime Database and displays the value in a table.
Her is my code:
var leadsRef = database.ref('leads/'+leadID);
var table = document.getElementById('remarksTable');
leadsRef.on('child_added', function(snapshot) {
var remark = snapshot.val().remark;
var timestamp = snapshot.val().timestamp;
var row = document.createElement('tr');
var rowData1 = document.createElement('td');
var rowData2 = document.createElement('td');
var rowData3 = document.createElement('td');
var rowDataText1 = document.createTextNode(remark);
var rowDataText2 = document.createTextNode(timestamp);
var rowDataText3 = document.createTextNode("Some text");
rowData1.appendChild(rowDataText1);
rowData2.appendChild(rowDataText2);
rowData3.appendChild(rowDataText3);
row.appendChild(rowData1);
row.appendChild(rowData2);
row.appendChild(rowData3);
table.appendChild(row);
});
leadID is an ID which I get from the current url, it contains the correct value so no issues there, path is also absolutely right.
Here is the table code:
<table class="table table-bordered" id="remarksTable">
<tr>
<th><strong>Created On</strong></th>
<th><strong>Timestamp 2</strong></th>
<th><strong>Remarks</strong></th>
</tr>
<tr>
<td>12312313231</td>
<td>12312312312</td>
<td>just a remark.</td>
</tr>
</table>
Now, when I run the page, it connects to the Firebase database and loads the required values, creates table row and table data, attaches text to it and then finally attaches the row to table with the id of remarksTable but it is not creating rows properly. Please note the table is creating using Bootstrap.
This is how it looks:
As you can see, the first row displays fine but the next 2 rows which were created by javascript looks a bit different.
The most likely reason is that you are appending the new row to the table element and not the tbody element inside it, which is interacting poorly with the stylesheet that you didn't include in the question.
Note that all tables have a tbody element. The start and end tags for it are optional so it will be inserted by HTML parsing rules if you don't provide one (or more) explicitly).
#Quentin is right, or you can simply add new rows this way:
var table = document.getElementById("remarksTable");
var row = table.insertRow();
var rowData1 = row.insertCell(0);
var rowData2 = row.insertCell(1);
var rowData2 = row.insertCell(2);
rowData1.innerHTML = remark;
rowData2.innerHTML = timestamp;
rowData3.innerHTML = "some text";
Here is a working demo
function addCells() {
var table = document.getElementById("remarksTable");
var row = table.insertRow();
var rowData1 = row.insertCell(0);
var rowData2 = row.insertCell(1);
var rowData3 = row.insertCell(2);
rowData1.innerHTML = "your remark";
rowData2.innerHTML = "your timestamp timestamp";
rowData3.innerHTML = "some text";
}
<table id="remarksTable" border=1>
<tr>
<td>first cell</td>
<td>2nd cell</td>
<td>3rd cell</td>
</tr>
</table>
<button onclick="addCells()">Add New</button>
I want to add a select (dropdown) to every row in my table.
The table is created using Javascript and has dynamic content imported from xml files using JQuery.
I managed to import all content successfully, however the dropdowns are displayed in the last row only.
I would appreciate if you can assist me to have the dropdown in every row.
Below is a code extract with blank selects only (the imported content is stored in those elements). All outputs such as "row " is for testing purpose only. "Numrows" are for testing purpose as well.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8" >
<title>table select test</title>
</head>
<body>
<table id="scrolltable">
</table>
<script type="text/javascript">
var tabbody = document.getElementById("scrolltable");
var types = document.createElement("select");
var units = document.createElement("select");
parseTable(3, types, "row ", units);
function parseTable(numrows, types, limits, units) {
for (i = 0; i < numrows; i++) {
var row = document.createElement("tr");
var cell1 = document.createElement("td");
cell1.style.width="300px";
cell1.appendChild(types);
row.appendChild(cell1);
var cell2 = document.createElement("td");
cell2.innerHTML = limits + i;
cell2.style.width = "100px";
row.appendChild(cell2);
var cell3 = document.createElement("td");
cell3.appendChild(units);
row.appendChild(cell3);
tabbody.appendChild(row);
}
}
</script>
</body>
</html>
types and units are defined once, so they are single elements. So they are moved to where you last called appendChild. If you want to see what happens, try adding alert(''); before ending your for loop and see it in action for every row.
If you want to add it in every row then you need new instances at each itterration:
function parseTable(numrows, types, limits, units) {
for (i = 0; i < numrows; i++) {
var row = document.createElement("tr");
var cell1 = document.createElement("td");
cell1.style.width="300px";
types = document.createElement("select");
cell1.appendChild(types);
row.appendChild(cell1);
var cell2 = document.createElement("td");
cell2.innerHTML = limits + i;
cell2.style.width = "100px";
row.appendChild(cell2);
var cell3 = document.createElement("td");
units = document.createElement("select");
cell3.appendChild(units);
row.appendChild(cell3);
tabbody.appendChild(row);
}
}
Without a minimum example, it may be difficult to pinpoint the issue, but my guess is:
You create the types and units elements only before your loop, so you are appending the same objects over and over, and each time you append one of them to a cell, you take it from the original cell and put it into the new one. Thats what "appendChild" does, it doesn't clone the element, it uses the same one (http://www.w3schools.com/jsref/met_node_appendchild.asp).
If you create a new select element in every step of your for, you should be fine =)
I'm delevoling an app with phonegap for android and I'm trying to make a FOR loop in javascript with html table rows. I tried using the document.write but all of the content in the page desapears, show just what it's in the document.write.
The code I have is this one:
<table id="hor-minimalist-b">
<script language=javascript>
for (var i=0; i<3; i++) {
document.write('<tr>');
document.write('<td>');
document.write('<input type="text" name="valor" id="valor" value="key' + i'">');
document.write('</td>');
document.write('</tr>');
}
</script>
</table>
Thanks.
It's because you are just putting text in the page, you need to "create" the element and append them to the table.
You can do it this way:
<table id="hor-minimalist-b"><thead></thead><tbody></tbody></table>
<script language="javascript">
var table = document.getElementById('hor-minimalist-b'); // get the table element
var tableBody = table.childNodes[1]; // get the table body
var tableHead = table.childNodes[0]; // get the table head
for (var i=0; i<3; i++) {
var row = document.createElement('tr'); // create a new row
var cell = document.createElement('td'); // create a new cell
var input = document.createElement('input'); // create a new input
// Set input properties
input.type = "text";
input.id = "valor"; // It's not a good idea (to have elements with the same id..)
input.name = "valor";
input.value = "key" + i;
cell.appendChild(input); // append input to the new cell
row.appendChild(cell); // append the new cell to the new row
tableBody.appendChild(row); // append the row to table body
}
</script>
insertRow() and insertCell() will probably work too, but I did not test it yet