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
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.
I am working on a project where I am finding difficulty in adding datetimepicker to dynamically added table rows. I have added datetimepicker to static table rows and it is working fine for them but not working for dynamically added table rows.
The tutorial I am following for datetimepicker
https://eonasdan.github.io/bootstrap-datetimepicker/
My Code I tried: I am cloning hidden rows.
Row Clone function:
// Table Add Function
$('.table-add').click(function () {
var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
hid = $TABLE.find('tr.hide').attr('id');
// //Assigning every table row a unique ID
var max=0;
$('table').find('tr').each(function(){
var id=parseInt($(this).attr('id'));
if (id>=max){
max = id;
}
});
//cloning row with new ID
$clone.attr('id', parseInt(max)+1);
//always assign new id to new table row, will be easy to recognize rows
$clone.find('input.myinput').attr('id', parseInt(max)+1);
$clone.find("[name='datepicker']").datetimepicker();
//$("[name='datepicker']").datetimepicker();
$hiddentr = $('table').find('tr.hide');
//add dynamic word picker to cloned rows dynamically
$clone.find('td:nth-last-child(4)').after('{% if obj.word_picker == "Y" %} <td><input id="wordpicker" style="border:none"; data-role="tagsinput" class="myinput" name="unique_tag"/></td>{% endif %}');
$clone.appendTo( $('#'+hid).parent());
//submitting form after row clone
submitForm();
});
HTML of hidden td:
<td>
<div style="position: relative">
<input class = "form-control" type= "text" name = "datepicker" id= "datetime">
</div>
</td>
Messy but just init datetimepisker each time after you add a row...
$('#datetimepicker1').datetimepicker();
$('#datetimepicker2').datetimepicker();
etc
I was able to initialize the datetimepicker once the element was completely generated into the dom. working codepen
function addTableRow() {
var tbodyElement = document.getElementById("tbody");
var trElement = document.createElement("tr");
trElement.id = "generatedTr";
for (var x=0; x<3; x++) {
var tdElement = document.createElement("td");
var textNode = document.createTextNode("Generated td: " + x);
tdElement.appendChild(textNode);
trElement.appendChild(tdElement);
}
var finalTdElement = document.createElement("td");
var inputElement = document.createElement("input");
inputElement.setAttribute("type", "text");
inputElement.id = "generatedInput";
finalTdElement.appendChild(inputElement);
trElement.appendChild(finalTdElement);
tbodyElement.appendChild(trElement);
$('#generatedInput').datetimepicker();
}
If you have multiple elements that are being generated that needs the datetime picker, then I would suggest creating a class on all of them, then simply instantiate the plugin against that class like so.
$('.dateTimePickers').datetimepicker();
I would suggest don't initialize the datetimepicker every time after each element. better use following code. It will work like a charm.
I have been doing lot of research for this. Thus, Recommending to use Following code.
$('body').on('focus',".datetimepicker", function(){
$(this).datetimepicker();
});
(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 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 =)
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/