I have Javascript like the following:
function addRow(table1) {
var table = document.getElementById(table1);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
}
}
}
And HTML like the following:
<input type="button" value="Insert row" onclick="addRow('table1')" />
<table id="table1" border=1>
<tr>
<td rowspan=2><input type="text" name="txt1"></td>
<td><input type="text" name="txt2"></td>
</tr>
<tr>
<td><input type="text" name="txt3"></td>
</tr>
</table>
I have a row with rowspan=2, and two rows with no rowspan. How do I write the following line so that once the user clicks the Insert Row button, three textboxes will be added into the new row?
newcell.innerHTML = table.rows[0].cells.innerHTML;
Note that in your code you have:
> newcell.innerHTML = table.rows[0].cells.innerHTML;
I think you mean:
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
But anyway, have you considered using a cloned row instead? e.g. something like the following (untested):
function addRow(tableID) {
var table = document.getElementById(tableID);
var row = table.rows[0].cloneNode(true);
var inputs = row.getElementsByTagName('input');
var i = inputs.length;
while (i--) {
if (inputs[i].type = 'text') {
inputs[i].vaule = '';
// Might want to change other properties too
}
}
table.tBodies[0].appendChild(row);
}
Related
I am trying to build a form for creating a list for image deployment.
I am able to create a dynamic table on form load and also collect the data for each value, but can seem to get the Add and Delete working.
My Question:
What must I do(or change) in my code to get the ADD and Delete options working and to export the table data in CSV format.
Please could someone help and/or guide me as I am getting so lost and really would like a working example .. there is so much on the net it's over-whelming
Newest place I visited is Mozilla DOM help pages what's confusing is how to load your own variables into the table
For reference I used stackoverflow and plenty google and finally this site
Here is my code:
<div id="metric_results">
Enter Target Name:
<input type="text" name="textbox1" id="textbox1" VALUE="win2k8"/>
<br>
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
<input type="button" id="create" value="Add Row" onclick="Javascript:addRow()">
<input type="button" id="create" value="Delete Row" onclick="Javascript:deleteRow()">
</div>
<SCRIPT LANGUAGE="JavaScript">
window.onload =addTable;//loads table on window loading
function addTable() {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
var imageName = textbox1.value
table.border = '1'
table.appendChild(tableBody);
var heading = new Array();
heading[0] = "imageName"
heading[1] = "acceptAllEula"
heading[2] = "noSSLverify"
heading[3] = "noVerification"
heading[4] = "TargetImagelocation"
heading[5] = "Username"
heading[6] = "Password"
heading[7] = "Target IP"
var imageInfo = new Array()
imageInfo[0] = new Array(imageName, "acceptAllEula", "noSSLverify", "noVerification", "testLocation", "user", "pass", "192.168.1.151")
imageInfo[1] = new Array("win2008", "acceptAllEula", "noSSLverify", "noVerification", "testLocation", "user", "pass", "192.168.1.151")
//TABLE COLUMNS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < heading.length; i++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[i]));
tr.appendChild(th);
}
//TABLE ROWS
for (i = 0; i < imageInfo.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < imageInfo[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(imageInfo[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table)
}
function addRow() {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
</SCRIPT>
You're not setting any id to the table you're creating onload - so when you later come to call getElementById() inside addRow it cannot be found (and you're using a variable which does not exist - tableID!)
My suggestion is to take an id as a parameter to addTable, and set that as the id of the dynamically generated table:
function addTable(id) {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
table.id = id;
....
onload, pass somethig sensible - default perhaps:
window.onload = function(){
addTable("default");
}
And either pass this in when adding a row, or use the default provided above:
function addRow() {
var table = document.getElementById("default");
....
or
function addRow(id) {
var table = document.getElementById(id);
Updated fiddle: https://jsfiddle.net/egtu5kay/5/
Left as an exercise for you: Correctly formatting the new row as you wish.
I'm using the following JavaScript function to add a row to my table. I want to write to the table the value of the current rowCount.
My function is:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
newcell.childNodes[0].value = rowCount;
}
}
My HTML table:
<TABLE id="dataTable" border="0">
<TR style="display:none;">
<TD><INPUT type="checkbox" name="chk2"/></TD>
<TD><script>document.write(rowCount);</script><select name="room[][]" multiple="MULTIPLE" >
<option value="" selected ></option>
</select></TD>
</TR>
</TABLE>
I have tried <script>document.write(rowCount);</script> and <script>document.write(this.rowCount);</script>. The first returning the error: Can't find variable rowCount and the second: undefined is not an object.
It sounds a bit messy but the idea is that I want to pass the rowCount value into the name of <select name="room[][]> giving me:
<select name="room[0][]>
<select name="room[1][]>
<select name="room[2][]>
I'm dynamically creating a table using an HTML table and JavaScript Functions attatched to button clicks. I now want to take the data and store it into multidimensional array (if possible) using another button named finished. I'm having trouble even getting started with the last method to save it into array. I can't figure out how to retrieve the text data.
Here is my current HTML code.
<head>
<title>TableTest</title>
<script src="/javascript/func.js"></script>
</head>
<body>
<form>
<div id="Input">
<INPUT class="form-button" id="AddRow" type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT class="form-button" id="DeleteRow" type="button" value="Delete Row(s)" onclick="deleteRow('dataTable')" />
<INPUT class="form-button" id="Finished" type="button" value="Finished" onclick="gatherData('dataTable')" />
<table id="dataTable" border="1" style="width:200px" id="mytable" align="center" cellspacing="3" cellpadding="4">
<th>Select</th>
<th>Text1</th>
<th>Text2</th>
<th>Text3</th>
<tr>
<td><INPUT type="checkbox" name="chk"/></td>
<td><INPUT type="text" name="text1"/></td>
<td><INPUT type="text" name="txt2"/></td>
<td><INPUT type="text" name="txt3"/></td>
</tr>
</table>
</div>
</form>
</body>
Here is my JavaScript file:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function gatherData(){
//Tests
var table = document.getElementById('dataTable');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
alert(rowCount);
alert(row);
alert(colCount);
}
I reworked TameBadger's answer to build the array by row instead of by column. I also added a check to see if the given cell has a value before referencing it. In my case, not all cells have values.
var table = document.getElementById('mainTable');
if (table === null)
return;
if (table.rows[0].cells.length <= 1)
return;
var tblData = [];
//Put a RowNumber name and values placeholder for the number of rows we have.
for (r = 0; r < table.rows.length; r++)
{
//Debug
//console.log(" row: ", r);
tblData.push({
name: "RowNumber" + r,
items: []
});
//Get the cells for this row.
var cells = table.rows[r].cells;
//Loop through each column for this row and push the value...
for (c = 0; c < cells.length; c++)
{
var inputElem = cells[c].children[0];
var tmpInputElem;
if (inputElem == null)
{
tmpInputElem = "";
}
else
{
tmpInputElem = inputElem.value
}
//Debug
//console.log(" row-cel: ", r, "-", c, " ", inputElem);
tblData[r].items.push(
{
//Comment out the type for now...
//inputType: inputElem.getAttribute('type'),
inputValue: tmpInputElem
});
}
}
//Debug
//printData(tblData);
I tried to keep it simple, and also jQuery clean, so to speak.
var data = [];
function gatherData() {
var table = document.getElementById('dataTable');
for (r = 1; r < table.rows.length; r++) {
var row = table.rows[r];
var cells = row.cells;
for (c = 0; c < cells.length; c++) {
var cell = cells[c];
var inputElem = cell.children[0];
var isInput = inputElem instanceof HTMLInputElement;
if (!isInput)
return;
var value = inputElem.value;
var isCheckbox = inputElem.getAttribute('type') == 'checkbox';
if (isCheckbox)
value = inputElem.checked;
var rowData = {};
rowData.inputType = inputElem.getAttribute('type');
rowData.inputValue = value;
data.push(rowData);
}
}
}
function startExec() {
gatherData();
for (i = 0; i < data.length; i++) {
console.log(data[i].inputType);
console.log(data[i].inputValue);
}
}
//just wait for the dom to load, and then execute the function for testing
document.addEventListener("DOMContentLoaded", startExec, false);
2nd Revision
function getData() {
var table = document.getElementById('dataTable');
if (table === null)
return;
if (table.rows[0].cells.length <= 1)
return;
var data = [];
for (l = 0; l < table.rows[0].cells.length; l++) {
data.push({
items: [],
name: "ColumnNumber" + l
});
}
for (i = 1; i < table.rows.length; i++) {
var cells = table.rows[i].cells;
for (c = 0; c < cells.length; c++) {
var inputElem = cells[c].children[0];
data[c].items.push({
inputType: inputElem.getAttribute('type'),
inputValue: inputElem.value
});
}
}
printData(data);
}
function printData(data) {
for (i = 0; i < data.length; i++) {
for (k = 0; k < data[i].items.length; k++) {
console.log(data[i].items[k].inputValue);
}
}
}
document.addEventListener("DOMContentLoaded", getData(), false);
It's great that you're starting off and doing the table manipulation yourself, and I would recommend continuing that, if you want to peak into a bigger codebase I would recommend checking out jTable's. Even though it's a jQuery plugin, you'll still be able to learn something from looking at the code structure for handling all the logic surrounding building a table according to a dataset and adding records etc.
Is this what you are looking for?
JSFIDDLE
$(document).ready(function(){
$('#Finished').click(function(){
var my_arr=[];
$('td').each(function(){
if ($(this).children().is(':checkbox') )
{
if($(this).children().prop('checked'))
{
my_arr.push($(this).children().val());
}
}else{
my_arr.push($(this).children().val());
}
})
console.log(my_arr);
})
})
We have a specific functionality where we need to add dynamic rows. In each of the row for the third column there is a button to add combo where it should be able to add extra combo in that cell. We have tried appendChild but is not working. Any idea how to add extra combo boxes. Below is the codes and function to do that is addSubRow.
<HTML>
<HEAD>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
newcell.innerHTML = newcell.innerHTML +"<br> TEST";
//alert(newcell.childNodes);
/*switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
newcell.childNodes[0].id = "input" + rowCount;
break;
case "checkbox":
newcell.childNodes[0].checked = false;
newcell.childNodes[0].id = "checkbox" + rowCount;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
newcell.childNodes[0].id = "select" + rowCount;
break;
}*
if(newcell.childNodes[0].type=="button")
{
alert("TEST");
newcell.childNodes[0].id=rowCount;
}*/
}
var table = document.getElementById(tableID);
var rows = table.getElementsByTagName('tr');
for (var i = 0, row; row = table.rows[i]; i++) {
row.id="row"+i;
row.name="row"+i;
var rowName = "row"+i;
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
col.id="col_"+i+"_"+j;
col.name="col_"+i+"_"+j;
var cels = rows[i].getElementsByTagName('td')[j];
var realKids = 0,count = 0;
kids = cels.childNodes.length;
while(count < kids){
if(cels.childNodes[i].nodeType != 3){
realKids++;
}
count++;
}
alert("I : "+i+" "+"J : "+j+" "+"realKids :"+cels.childElementCount);
//alert();
}
}
}
function addSubRow(tableID,colID) {
var tdID = document.getElementById(colID);
var table = document.getElementById(tableID);
var comboBox1 = table.rows[0].cells[2].childNodes[1];
comboBox1 = comboBox1;
tdID.appendChild(comboBox1);
//tdID.appendChild(comboBox1);
//tdID.appendChild(comboBox1);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
var table = document.getElementById(tableID);
for (var i = 0, row; row = table.rows[i]; i++) {
row.id="row"+i;
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
//alert("J : "+j);
col.id="col"+i;
if(j==0)
{
}
else if(j==1)
{
}
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD><INPUT type="text" name="txt"/></TD>
<TD id="col_0_2">
<INPUT type="button" value="Add Combo" onclick="addSubRow('dataTable','col_0_2')" />
<SELECT name="country">
<OPTION value="in">India</OPTION>
<OPTION value="de">Germany</OPTION>
<OPTION value="fr">France</OPTION>
<OPTION value="us">United States</OPTION>
<OPTION value="ch">Switzerland</OPTION>
</SELECT>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
I'm not sure if this is what you really want, but here's a working function addSubRow function for appending a combobox.
I added some comments to explain what I did:
function addSubRow(tableID,colID) {
var tdID = document.getElementById(colID);
var table = document.getElementById(tableID);
// Create a new combobox element
var new_comboBox = document.createElement('select');
// Define / Add new combobox's attributes here
//new_comboBox.setAttribute('id', 'something');
// ...
// ...
// Add new combobox's options - you may use a 'for' loop...
var option_1 = document.createElement('option');
option_1.setAttribute('value', '1');
var txt_1 = document.createTextNode("OPTION 1");
option_1.appendChild(txt_1);
var option_2 = document.createElement('option');
option_2.setAttribute('value', '2');
var txt_2 = document.createTextNode("OPTION 2");
option_2.appendChild(txt_2);
var option_3 = document.createElement('option');
option_3.setAttribute('value', '3');
var txt_3 = document.createTextNode("OPTION 3");
option_3.appendChild(txt_3);
// ...
// ...
// Appending options to the new combobox
new_comboBox.appendChild(option_1);
new_comboBox.appendChild(option_2);
new_comboBox.appendChild(option_3);
// ...
// ...
// Appending the combobox to the TD
tdID.appendChild(new_comboBox);
}
PS:
Pay attention when defining the combobox's attributes and its options' attributes
I don't think that you need to use the table's ID tableID, in your function. You may simplify your function addSubRow by rmoving this argument?
Hope this helps mate.
I have a HTML form which allows a user to add rows ad hoc using JavaScript.
The Form:
<form method="post" action="send.php">
<table id="table">
<tr><th>job</th><th>comment</th></tr>
<tr>
<td><textarea name = "job[]"></textarea></td>
<td><textarea name = "comment[]"></textarea></td>
<tr>
</table>
<input type ="button" value="add entry" onclick="add('table')"/>
<input type ="submit" id="submit" value="submit"/>
The JavaScript:
function add(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
var newentry = document.createElement('textarea');
newentry.type = "text";
newcell.appendChild(newentry);
}
}
The PHP code
$job = $_POST['job'];
$comment = $_POST['comment'];
//code to connect to database
$add_stmt = $mysqli->prepare("INSERT INTO job (job, comment) VALUES (?, ?)");
$foreach($job as $a => $b) {
$add_stmt->bind_param("ss", $job[$a], $comment[$a]);
$add_stmt->execute();
}
When I click on the "add entry" button, a row will be successfully created. However, only data in the first row will be submitted to the database. Using
echo "row count is" . count($_POST['job']);
I got "row count is 1" even though I have several rows of data.
Can somebody figure out what might have gone wrong with my code? Thanks a bunch!
You have to set name property for fields that you add:
// create array with names
var names = ['job[]', 'comment[]'];
function add(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
var newentry = document.createElement('textarea');
newentry.type = "text";
// set name
newentry.name = names[i];
newcell.appendChild(newentry);
}
}
You can try make two files: index.html and send.php and insert this content:
index.html:
<html>
<head>
<script>
var names = ["job[]", "comment[]"];
function add(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
var newentry = document.createElement('textarea');
newentry.name = names[i];
newentry.type = "text";
newcell.appendChild(newentry);
}
}
</script>
</head>
<body>
<form method="post" action="send.php">
<table id="table">
<tr><th>job</th><th>comment</th></tr>
<tr>
<td><textarea name = "job[]"></textarea></td>
<td><textarea name = "comment[]"></textarea></td>
<tr>
</table>
<input type ="button" value="add entry" onclick="add('table')"/>
<input type ="submit" id="submit" value="submit"/>
</form>
</body>
</html>
send.php:
<?php
$job = $_POST['job'];
$comment = $_POST['comment'];
var_dump($job);
var_dump($comment);
?>
And run on you server - this works for me. Make sure that you have names set properly.