Add Rows and Cols to a HTML Table - javascript

I'm trying to figure out how to add a new row to a table using Javascript but I also need to be able to add 3 columns into this table and here is where I am having problems. I can't seem to get it to work. Here is the javascript:
This adds rows with first field being ID entered into the first row but I don't know how to fill in columns.
function myCreateFunction() {
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++) {
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var div1 = document.createElement('div');
div1.innerHTML = "ID";
cell1.appendChild(div1);
div1.contentEditable = true;
}
}
Here is my Table:
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>

try this
function myCreateFunction(thisObj) {
var buttonTr = thisObj.parentNode.parentNode;
var buttonTrHTML = buttonTr.outerHTML;
buttonTr.parentNode.removeChild(buttonTr);
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++)
{
table.innerHTML += "<tr><td>ID</td> <td>First Name</td><td>Last Name</td> <td>Add More</td><tr>";
}
//table.innerHTML += buttonTrHTML ;
table.appendChild(buttonTr );
}
and you need to pass the current Obj as
<button onclick="myCreateFunction(this)">Create row</button>

Try this
function myCreateFunction() {
var table = document.getElementById("myTable");
var rows = table.rows.length;
var row = table.insertRow(rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = "ID";
cell1.contentEditable = true;
cell2.innerHTML = "First Name";
cell2.contentEditable = true;
cell3.innerHTML = "Last Name";
cell3.contentEditable = true;
var but1 = document.createElement('button');
but1.innerHTML = "Create row";
but1.setAttribute("onclick", "myCreateFunction()");
cell4.appendChild(but1);
var but2 = document.createElement('button');
but2.innerHTML = "Delete row";
but2.setAttribute("onclick", "myDeleteFunction()");
cell4.appendChild(but2);
}
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button><button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>

I solved this a bit different. And it works fine (also with deleting rows):
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var maxRows = 10;
if (rowCount < maxRows) {
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;
}
} else {
alert("Max. Tabs= " + maxRows);
}
}
function deleteRow(tableID) {
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 (chkbox != null && chkbox.checked == true) {
if (rowCount <= 1) {
alert("Min Tabs = 1");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}

Try following function
function myCreateFunction() {
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
console.log(rowCount)
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = rowCount;
cell2.innerHTML = ""; //put your text/html here
cell2.innerHTML = ""; //put your text/html here
}
put your desired text or html in innerHTML of the respected cell
Also for Pavel's answer your markup is wrong(though I haven't tested the function). The table id 'myTable' should be passed as string.
<button onclick="addRow('myTable')">Create row</button>
could not comment for not having enough reputation
Hope this helps.

Related

How to get table row value into text field in JavaScript..?

I Create a Table Using this code,
<table class="table table-green table-hover" id="tblk"></table>
And I Use This JavaScrip Function (For A Button) to add Rows when I add data in to table,
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
}
When I clicked a table row, I need to get a table Row value into my input text field
This Is my JavaScrip Function to get table rows to value into my text field..,
var table = document.getElementById('tblk'),
rIndex
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function () {
document.getElementById('InputCusomerID').value = this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = this.cells[1].innerHTML
document.getElementById('InputItemID').value = this.cells[2].innerHTML
}
}
But My Code Is Not Working I Can't Get Table Row Value Into My Text Field.
Can You Help Me With That Problem..?
Thank You Very Much..!
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
}
var table = document.getElementById('tblk'),
rIndex
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
document.getElementById('InputCusomerID').value = this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = this.cells[1].innerHTML
document.getElementById('InputItemID').value = this.cells[2].innerHTML
}
}
<table class="table table-green table-hover" id="tblk"></table>
I don't know exactly what you're trying to do, but it's not working because your click listener is being called before your table is populated. See my code.
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
setListeners();
}
var table = document.getElementById('tblk'),
rIndex;
function setListeners() {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].addEventListener('click', function (e) {
console.log(e.target);
document.getElementById('InputCusomerID').value = "result: " + this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = "result: " + this.cells[1].innerHTML
document.getElementById('InputItemID').value = "result: " + this.cells[2].innerHTML
});
}
}
addRow();
<input type="text" id="InputCusomerID" value="a" />
<input type="text" id="InputCusomerName" value="b" />
<input type="text" id="InputItemID" value="c" />
<table class="table table-green table-hover" id="tblk"></table>

How do I get html multiple row table data to Javascript

HTML table
<table id="dataTable" border="1px" style="width:355px; BORDER-COLLAPSE:collapse">
<tr>
<td id="0" align="center"></td>
<td id="1" align="center">Name</td>
<td id="2" align="center">Designation</td>
<td id="3" align="center">PAN</td>
<td id="4" align="center">Address</td>
</tr>
<tr>
<td><input type="checkbox" name="chk" id ="chk" size="6"/></td>
<td><input type="text" name="txtRow1" id="txtRow1" size="8"/></td>
<td><input type="text" name="txtRow2" id="txtRow2" size="8"/></td>
<td><input type="text" name="txtRow3" id="txtRow3" size="8"/></td>
<td><input type="text" name="txtRow4" id="txtRow4" size="8"/></td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="Add Row" onclick="addRowTable('dataTable')" /></td>
<td><input type="button" value="Delete Row" onclick="deleteRowTable('dataTable')" /></td>
</tr>
</table>
After entering data into HTML table, I want to get that data to javascript so that I could save it in the database. The HTML table contains multiple rows and four columns. User can add rows if they want to add column to enter data. I want to get all the column data to the javascript. How do I do that..Kindly help me
My HTML Code:
function addRowTable(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount > 10) {
alert("Maximum 10 rows allowed");
return false;
}
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chkbox[]";
cell1.appendChild(element1);
element1.size = 8;
/*var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;*/
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell2.appendChild(element2);
element2.size = 8;
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
cell3.appendChild(element3);
element3.size = 8;
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtbox[]";
cell4.appendChild(element4);
element4.size = 8;
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "txtbox[]";
cell5.appendChild(element5);
element5.size = 8;
}
function deleteRowTable(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);*/
}
}
My javascript code to add and delete table rows:
Now after table columns are filled, i want to get that data to javascript.I tried to do like below. But it is not working.I am getting null values.I am not getting the actual values.
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++)
{
var Name = $("dataTable").find("tr").eq(i).find("td").eq(0).text();
var Designation = $("dataTable").find("tr").eq(i).find("td").eq(1).text();
var PAN = $("dataTable").find("tr").eq(i).find("td").eq(2).text();
var Address = $("dataTable").find("tr").eq(i).find("td").eq(3).text();
}
Kindly let me know what am I doing wrong and what should I do.
Thank You!
The data of an HTML table can be stored in a JS array, it's easier than putting the data into variables (which are storing the last row only).
var rows = table.rows,
len = rows.length,
data = [],
cells;
for (var n = 1; n < len; n++) {
cells = rows[n].cells;
data.push([
cells[0].firstElementChild.checked,
cells[1].firstElementChild.value,
cells[2].firstElementChild.value,
cells[3].firstElementChild.value,
cells[4].firstElementChild.value
]);
}
Now it's easy to read the values from data array when needed.
You are on the right way, but pay attention to some details:
In your solution you select the 'td' not the input inside it.
If you use an input you cannot get the innterText by calling .text() instead you want to use the .val() method to receive the
value
Name your inputs consistently. In your first row you name them "txtRow1"-"textRow4" ... but when you add new rows you name them
"txtbox[]": First of all i think you mean txtCol not txtRow ... just think about it. Second you if you want to group your inputs by column then append the "[]" brackets to the names that belong together like so "txtCol1[]" - "txtCol4[]"
I have put it all together for you:
function addRowTable(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount > 10) {
alert("Maximum 10 rows allowed");
return false;
}
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chkbox[]";
cell1.appendChild(element1);
element1.size = 8;
/*var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;*/
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtCol1[]";
cell2.appendChild(element2);
element2.size = 8;
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtCol2[]";
cell3.appendChild(element3);
element3.size = 8;
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtCol3[]";
cell4.appendChild(element4);
element4.size = 8;
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "txtCol4[]";
cell5.appendChild(element5);
element5.size = 8;
}
function deleteRowTable(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);*/
}
}
function readData(tableID){
var rowCount = $(tableID + ' tr').length;
var results = [];
for (var i = 1; i < rowCount; i++)
{
results.push({
Name: $(tableID).find('tr').eq(i).find('[name="txtCol1[]"]').val(),
Designation: $(tableID).find('tr').eq(i).find('[name="txtCol2[]"]').val(),
PAN: $(tableID).find('tr').eq(i).find('[name="txtCol3[]"]').val(),
Address: $(tableID).find('tr').eq(i).find('[name="txtCol4[]"]').val(),
});
}
console.log(results);
return results;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="dataTable" border="1px" style="width:355px; BORDER-COLLAPSE:collapse">
<tr>
<td id="0" align="center"></td>
<td id="1" align="center">Name</td>
<td id="2" align="center">Designation</td>
<td id="3" align="center">PAN</td>
<td id="4" align="center">Address</td>
</tr>
<tr>
<td><input type="checkbox" name="chkbox[]" id="chk" size="6" /></td>
<td><input type="text" name="txtCol1[]" id="txtCol1" size="8" /></td>
<td><input type="text" name="txtCol2[]" id="txtCol2" size="8" /></td>
<td><input type="text" name="txtCol3[]" id="txtCol3" size="8" /></td>
<td><input type="text" name="txtCol4[]" id="txtCol4" size="8" /></td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="Add Row" onclick="addRowTable('dataTable')" /></td>
<td><input type="button" value="Delete Row" onclick="deleteRowTable('dataTable')" /></td>
<td><input type="button" value="Read Data" onclick="readData('#dataTable')" /></td>
</tr>
</table>

Add function not working

I wrote below the javascript which will allow user to add and delete the row and calculate the weighting. The addition and deletion are working fine but I believe I am unable to do sum of weighting. Can you please advise ?
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtbox[]";
element4.class = "wtotal1";
cell4.appendChild(element4);
}
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);
}
}
function weighttotal1(){
var tweight1 = 0;
var cusid_ele = document.getElementsByClassName('wtotal1');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseFloat(cusid_ele[i].textContent)) )
tweight1 += parseFloat(cusid_ele[i].textContent);
}
document.getElementById('tweight1').value=tweight1;
}
<table id="dataTable1" class="table table-condensed table-hover table-responsive table-striped table-bordered">
<tbody>
<tr>
<th></th>
<th>ComponentId</th>
<th>Component Description</th>
<th>Weighting</th>
</tr>
</tbody>
</table>
<br>
<div class="col-sm-6">
<div class="form-inline">
<input class="form-control input-sm" name="tweight" type="text" id="tweight1" value="" readonly>
<button onclick="weighttotal1()">Weigthing total</button>
</div>
</div>
Two things:
1.- Replaces the attribute
element4.class = "wtotal1"; By element4.className = "wtotal1";
2 replaces the cusid_ele[i].textContent attribute with cusid_ele[i].value
The complet code
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtbox[]";
element4.className = "wtotal1";
cell4.appendChild(element4);
}
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);
}
}
function weighttotal1(){
var tweight1 = 0;
var cusid_ele = document.getElementsByClassName('wtotal1');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseFloat(cusid_ele[i].value)) )
tweight1 += parseFloat(cusid_ele[i].value);
}
document.getElementById('tweight1').value=tweight1;
}
</script>
<table id="dataTable1" class="table table-condensed table-hover table-responsive table-striped table-bordered">
<tbody>
<tr>
<th></th>
<th>ComponentId</th>
<th>Component Description</th>
<th>Weighting</th>
</tr>
</tbody>
</table>
<br>
<div class="col-sm-6">
<div class="form-inline">
<button onclick="addRow('dataTable1')">Add Row</button><button
onclick="deleteRow('dataTable1')">Delete Row</button>
<br>
<br>
<input class="form-control input-sm" name="tweight" type="text" id="tweight1" value="" readonly>
<button onclick="weighttotal1()">Weigthing total</button>
</div>
</div>

Update Table rows onClick Events and Remove Previouslly added

I want to add new row, and remove previously added row with an onclick event.
I write code for it but this code only insert rows not delete previous one.
js
function addRow(tableID) {
console.log('hi')
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
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);
}
html
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<table id="dataTable" border="1">
<tr>
</tr>
</table>
Use deleteRow().. and you might just be able to do it.
function addRow(tableID) {
console.log('hi')
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount) {
table.deleteRow(-1);
}
...
}

Form within table contains dynamically created input parameters that are not being passed in IE 9 and 10

var i = 0;
var a = 3;
function addNewAnswer(tableID) {
var table = document.getElementById(tableID);
if(i < 10)
{
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = '<font size="2" face="Courier New"><b>Enter Answer ' + String.fromCharCode(67+i) + ':</b></font>';
var cell2 = row.insertCell(1);
var element1 = document.createElement("input");
element1.size = 40;
element1.type = "text";
element1.name = "answer"+a;
cell2.appendChild(element1);
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "radio";
element2.name = "radios";
element2.value = String.fromCharCode(67+i);
cell3.appendChild(element2);
i++;
a++;
}
}
My HTML Form:
<table>
<tr>
<form method=post name="submitform" action="verify-qedit.jsp">
<td>
<form method=post name="submitform" action="verify-qedit.jsp">
<table id="dataTable">
<tr>
<th colspan="3" align="left">Question</th>
</tr>
</table>
</form>
</td>
</form>
</tr>
</table>
When I submit the form, I only can retrieve the parameters not created by the above javascript. It only works in compatibility mode - IE 8 standards and below. Please help because I have spent days trying to find out before posting this question.
Does this work on all the browsers you are targetting?
http://jsfiddle.net/4nbB5/1
function addNewAnswer(tableID) {
var rowCount, row, cell1, cell2, cell3, element1, element2, char;
var i = 0;
var table = document.getElementById(tableID);
while (i < 10) {
rowCount = table.rows.length;
row = table.insertRow(rowCount);
cell1 = row.insertCell(0);
char = String.fromCharCode(65 + i);
cell1.innerHTML = '<font size="2" face="Courier New"><b>Enter Answer ' + char + ':</b></font>';
cell2 = row.insertCell(1);
element1 = document.createElement("input");
element1.size = 40;
element1.type = "text";
element1.name = "answer" + i;
cell2.appendChild(element1);
cell3 = row.insertCell(2);
element2 = document.createElement("input");
element2.type = "radio";
element2.name = "radios";
element2.value = char;
cell3.appendChild(element2);
i++;
}
}
addNewAnswer('foo');
All I did was remove 'a', and declare 'i', change 'if' to while, changed 67 in fromCharCode to 65.. Looked to be what you may have wanted at some point so I stopped.
The problem had nothing to do with the javascript. It was because I was putting the form tag in the wrong place within the table after the tr tag instead of after the td tag.
<table>
<tr>
<td>
<form method=post name="submitform" action="verify-qedit.jsp">
<table id="dataTable">
<tr>
<th colspan="3" align="left">Question</th>
</tr>
</table>
</form>
</td>
</tr>
</table>

Categories