I have an HTML table with a header and a footer:
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
<tfoot>
</table>
I am trying to add a row in tbody with the following:
myTable.insertRow(myTable.rows.length - 1);
but the row is added in the tfoot section.
How do I insert tbody?
If you want to add a row into the tbody, get a reference to it and call its insertRow method.
var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var newCell = newRow.insertCell();
// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>initial row</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My Footer</td>
</tr>
</tfoot>
</table>
(old demo on JSFiddle)
You can try the following snippet using jQuery:
$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
Basic approach:
This should add HTML-formatted content and show the newly added row.
var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
I think this script is what exactly you need
var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)
You're close. Just add the row to the tbody instead of table:
myTbody.insertRow();
Just get a reference to tBody (myTbody) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.
A live demo is at jsFiddle.
Add rows:
<html>
<script>
function addRow() {
var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e = table.rows.length-1;
var l = table.rows[e].cells.length;
//x.innerHTML = " ";
for (var c=0, m=l; c < m; c++) {
table.rows[0].insertCell(c);
table.rows[0].cells[c].innerHTML = " ";
}
}
function addColumn() {
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].insertCell(0);
table.rows[r].cells[0].innerHTML = " ";
}
}
function deleteRow() {
document.getElementById("myTable").deleteRow(0);
}
function deleteColumn() {
// var row = document.getElementById("myRow");
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].deleteCell(0); // var table handle
}
}
</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
<input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
<input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
<input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>
<table id='myTable' border=1 cellpadding=0 cellspacing=0>
<tr id='myRow'>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
And cells.
let myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];
let row = myTable.insertRow();
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);
cell1.innerHTML = 1;
cell2.innerHTML = 'JAHID';
cell3.innerHTML = 23;
row = myTable.insertRow();
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell1.innerHTML = 2;
cell2.innerHTML = 'HOSSAIIN';
cell3.innerHTML = 50;
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #000;
padding: 10px;
}
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
</tr>
</thead>
<tbody></tbody>
</table>
Add Column, Add Row, Delete Column, Delete Row. Simplest way
function addColumn(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
for(i=0;i<row.length;i++){
row[i].innerHTML = row[i].innerHTML + '<td></td>';
}
}
function deleterow(tblId)
{
var table = document.getElementById(tblId);
var row = table.getElementsByTagName('tr');
if(row.length!='1'){
row[row.length - 1].outerHTML='';
}
}
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
function myFunction(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].outerHTML;
table.innerHTML = table.innerHTML + row;
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].getElementsByTagName('td');
for(i=0;i<row.length;i++){
row[i].innerHTML = '';
}
}
table, td {
border: 1px solid black;
border-collapse:collapse;
}
td {
cursor:text;
padding:10px;
}
td:empty:after{
content:"Type here...";
color:#cccccc;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<p>
<input type="button" value="+Column" onclick="addColumn('tblSample')">
<input type="button" value="-Column" onclick="deleteColumn('tblSample')">
<input type="button" value="+Row" onclick="myFunction('tblSample')">
<input type="button" value="-Row" onclick="deleterow('tblSample')">
</p>
<table id="tblSample" contenteditable><tr><td></td></tr></table>
</form>
</body>
</html>
You can also use querySelector to select the tbody, then insert a new row at the end of it.
Use append to insert Node or DOMString objects to a new cell, which will then be inserted into the new row.
var myTbody = document.querySelector("#myTable>tbody");
var newRow = myTbody.insertRow();
newRow.insertCell().append("New data");
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
I have tried this, and this is working for me:
var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);
You can use the following example:
<table id="purches">
<thead>
<tr>
<th>ID</th>
<th>Transaction Date</th>
<th>Category</th>
<th>Transaction Amount</th>
<th>Offer</th>
</tr>
</thead>
<!-- <tr th:each="person: ${list}" >
<td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
</tr>
-->
<tbody id="feedback">
</tbody>
</table>
JavaScript file:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
// var json = "<h4>Ajax Response</h4><pre>" + JSON.stringify(data, null, 4) + "</pre>";
// $('#feedback').html(json);
//
console.log("SUCCESS: ", data);
//$("#btn-search").prop("disabled", false);
for (var i = 0; i < data.length; i++) {
//$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
$('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');
alert(data[i].accountNumber)
}
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR: ", e);
$("#btn-search").prop("disabled", false);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<div id="myDiv">
<label for="name">Name:</label>
<input
type="text"
name="myInput"
id="myInput"
placeholder="Name of expense"
size="50"
/><br /><br />
<label for="date">Date:</label>
<input type="date" id="myDate" name="myDate" />
<label for="amount">Amount:</label>
<input
type="text"
name="myAmount"
id="myAmount"
placeholder="Dollar amount ($)"
/><br /><br />
<span onclick="addRow()" class="addBtn">Add Expense</span>
</div>
<br />
<input type="button" value="Add Rows" onclick="addRows()" />
<!-- Optional position -->
<table id="myTable">
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Delete</th>
</tr>
<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>
</table>
<script>
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
function addRows() {
console.log("add rows");
document.getElementById("myTable").innerHTML += `<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>`;
}
</script>
</body>
</html>
$("#myTable tbody").append(tablerow);
Related
how to create textbox/text field and button
JavaScript
<script type="text/javascript">
function addItemTodo(){
var value = document.getElementById('item1').value;
var value2 = document.getElementById('item2').value;
var my_table = document.getElementById('todo');
var rows = my_table.getElementsByTagName("tr").length;
row = my_table.insertRow(rows);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell1.innerHTML = value;
cell2.innerHTML = value2;
}
</script>
HTML Code
<input type="text" id="item1" placeholder="item1" size="12">
<input type="text" id="item2" placeholder="item2" size="14">
<button id="add" onclick="addItemTodo()">Add</button>
<table border="1" style="width:50%" id="todo">
<tr>
<th>Input from 'item1'</th>
<th>Input from 'item2'</th>
<th>Text Box</th>
<th>Button</th>
</tr>
</table>
How to append the text box and button, when clicked the add button
You could create your new elements within your Javascript as strings, and then add them to two new cells (insertCell(2) and insertCell(3)) using .innerHTML like so:
function addItemTodo() {
var value = document.getElementById('item1').value;
var value2 = document.getElementById('item2').value;
var my_table = document.getElementById('todo');
var rows = my_table.getElementsByTagName("tr").length;
var row = my_table.insertRow(rows);
row.insertCell(0).innerHTML = value;
row.insertCell(1).innerHTML = value2;
row.insertCell(2).innerHTML = "<input type='text' placeholder='xxx' class='text-box' />";
row.insertCell(3).innerHTML = "<button>Text</button>";
}
.text-box {
width: 50px;
}
<input type="text" id="item1" placeholder="item1" size="12">
<input type="text" id="item2" placeholder="item2" size="14">
<button id="add" onclick="addItemTodo()">Add</button>
<table border="1" style="width:50%" id="todo">
<tr>
<th>Input from 'item1'</th>
<th>Input from 'item2'</th>
<th>Text Box</th>
<th>Button</th>
</tr>
</table>
This is my index and js file. When I click on the first table row it works but when I click on it again, it doesn't work. It works only one time for one table. Same thing is happening in the second table. I have also given the class name in the js file. Why it does not consider class name. Please explain it also.
var t1 = [];
var t2 = [];
$('.table2 tr').each(function(row, tr) {
t2[row] = $(tr).find('td:eq(0)').text()
});
$('.table1 tr').each(function(row, tr) {
t1[row] = $(tr).find('td:eq(0)').text()
});
$(".addRow").on("click", function() {
var $delete = $(this).find("td:eq(0)").text();
t2.push($delete);
t1.splice($.inArray($(this).find("td:eq(0)").text(), t1), 1);
var tbody2 = $('.body2');
$(".table2 tr").remove();
for (var i = 0; i < t2.length; i++) {
var tr = $('<tr class="deleteRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
var tbody1 = $('.body1');
$(".table1 tr").remove();
for (var i = 0; i < t1.length; i++) {
var tr = $('<tr class="addRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
});
$(".deleteRow").on("click", function() {
var $add = $(this).find("td:eq(0)").html();
t1.push($add);
t2.splice($.inArray($(this).find("td:eq(0)").text(), t2), 1);
var tbody1 = $('.body1');
$(".table1 tr").remove();
for (var i = 0; i < t1.length; i++) {
var tr = $('<tr class="addRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
var tbody2 = $('.body2');
$(".table2 tr").remove();
for (var i = 0; i < t2.length; i++) {
var tr = $('<tr class="addRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
});
<!DOCTYPE html>
<html>
<head>
<title>Table Manipulation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
>
</script>
</head>
<body>
<div class="row">
<div class="col-lg-4 col-md-4 col-lg-offset-2 col-md-offset-2 available">
<label>Available Members</label>
<table class="table table-bordered table1">
<tbody class="body1">
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Tabrez</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Akash</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Keshav</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Harsh</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-4 col-md-4 selected">
<label>Selected Members</label>
<table class="table table-bordered table2">
<tbody class="body2">
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Varun</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Shanu</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Salvi</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Piyush</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="table.js"></script>
</body>
</html>
Attach event (click) by using jQuery's .on(). Some possible changes you can make:
$("tbody").on("click",".addRow", function() {......
And
$("tbody").on("click",".deleteRow", function() {......
Also I think you are mistakenly adding class="addRow" instead of class="deleteRow" in the second for loop of .deleteRow click in the second table:
var tr = $('<tr class="deleteRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody2);
var t1 = [];
var t2 = [];
$('.table2 tr').each(function(row,tr){
t2[row]=$(tr).find('td:eq(0)').text()
});
$('.table1 tr').each(function(row,tr){
t1[row]=$(tr).find('td:eq(0)').text()
});
$("tbody").on("click",".addRow", function() {
var $delete = $(this).find("td:eq(0)").text();
t2.push($delete);
t1.splice($.inArray($(this).find("td:eq(0)").text(),t1),1);
var tbody2 = $('.body2');
$(".table2 tr").remove();
for(var i = 0;i < t2.length;i++){
var tr = $('<tr class="deleteRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
var tbody1 = $('.body1');
$(".table1 tr").remove();
for(var i = 0;i < t1.length;i++){
var tr = $('<tr class="addRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
});
$("tbody").on("click",".deleteRow", function() {
var $add = $(this).find("td:eq(0)").html();
t1.push($add);
t2.splice($.inArray($(this).find("td:eq(0)").text(),t2),1);
var tbody1 = $('.body1');
$(".table1 tr").remove();
for(var i = 0;i < t1.length;i++){
var tr = $('<tr class="addRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
var tbody2 = $('.body2');
$(".table2 tr").remove();
for(var i = 0;i < t2.length;i++){
var tr = $('<tr class="deleteRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
});
<!DOCTYPE html>
<html>
<head>
<title>Table Manipulation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">></script>
</head>
<body>
<div class="row">
<div class="col-lg-4 col-md-4 col-lg-offset-2 col-md-offset-2 available">
<label>Available Members</label>
<table class="table table-bordered table1">
<tbody class="body1">
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Tabrez</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Akash</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Keshav</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Harsh</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-4 col-md-4 selected">
<label>Selected Members</label>
<table class="table table-bordered table2">
<tbody class="body2">
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Varun</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Shanu</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Salvi</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Piyush</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="table.js"></script>
</body>
</html>
In your code you are not specifying the selector in .on() function.
If selector is omitted or is null, the event handler is referred to
as direct.
When a selector is provided, the event handler is referred to as
delegated.
An event-delegation (direct) approach attaches an event handler to
only one element, the tbody.
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on()
So you need to provided a selector for .on() function as below.
$('.table1').on('click', '.addRow', function() {})
$('.table2').on('click', '.deleteRow', function() {})
Delegated event handlers have the advantage that they can process
events from descendant elements that are added to the document at a
later time.
Source: http://api.jquery.com/on/
Also, you have an error in deleteRow functionality and fixed in below complete example.
var t1 = [];
var t2 = [];
$('.table2 tr').each(function(row, tr) {
t2[row] = $(tr).find('td:eq(0)').text()
});
$('.table1 tr').each(function(row, tr) {
t1[row] = $(tr).find('td:eq(0)').text()
});
$('.table1').on('click', '.addRow', function() {
var $delete = $(this).find("td:eq(0)").text();
t2.push($delete);
t1.splice($.inArray($(this).find("td:eq(0)").text(), t1), 1);
var tbody2 = $('.body2');
$(".table2 tr").remove();
for (var i = 0; i < t2.length; i++) {
var tr = $('<tr class="deleteRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
var tbody1 = $('.body1');
$(".table1 tr").remove();
for (var i = 0; i < t1.length; i++) {
var tr = $('<tr class="addRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
});
$('.table2').on('click', '.deleteRow', function() {
var $add = $(this).find("td:eq(0)").html();
t1.push($add);
t2.splice($.inArray($(this).find("td:eq(0)").text(), t2), 1);
var tbody1 = $('.body1');
$(".table1 tr").remove();
for (var i = 0; i < t1.length; i++) {
var tr = $('<tr class="addRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
var tbody2 = $('.body2');
$(".table2 tr").remove();
for (var i = 0; i < t2.length; i++) {
var tr = $('<tr class="deleteRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
});
<!DOCTYPE html>
<html>
<head>
<title>Table Manipulation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
>
</script>
</head>
<body>
<div class="row">
<div class="col-lg-4 col-md-4 col-lg-offset-2 col-md-offset-2 available">
<label>Available Members</label>
<table class="table table-bordered table1">
<tbody class="body1">
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Tabrez</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Akash</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Keshav</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Harsh</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-4 col-md-4 selected">
<label>Selected Members</label>
<table class="table table-bordered table2">
<tbody class="body2">
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Varun</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Shanu</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Salvi</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Piyush</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="table.js"></script>
</body>
</html>
The following HTML file contains an add button. When clicked, it should add a row. When I inspect the code, I find the rows added under the thead not the tbody tag. Why is that? how to avoid this?
addButton = document.getElementById("add-button");
table = document.getElementById("data-table");
addButton.addEventListener('click', add, false);
function add() {
var tableLength = table.length;
var row = table.insertRow(tableLength);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = "col1";
col2.innerHTML = "col2";
}
var delLink = document.getElementById("delete-link");
delLink.addEventListener('click', del, false);
function del() {
var rowstoDelete = table.querySelectorAll("tbody tr");
[].slice.call(rowstoDelete).forEach(function(row) {
row.remove()
});
}
<table align="center" cellspacing=1 cellpadding=1 id="data-table" border=1 class="data-table">
<thead>
<tr id="head" class="head">
<th class="head">Name</th>
<th class="head">Action</th>
</tr>
<tr id="initial-row" class="initial-row">
<th><input type="text" id="text-field"></th>
<th><input type="button" class="add-button" id="add-button" value="Add"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<a id="delete-link" href="#"> Delete all rows Except the first two</a>
check my fiddle here
enter link description here
What you didnt did is to see specifically for tbody. Answered here How to insert row in HTML table body in javascript?
addButton=document.getElementById("add-button");
table=document.getElementById("data-table");
addButton.addEventListener('click',add,false);
function add()
{
var tableLength=table.length;
var row = table.getElementsByTagName('tbody')[0].insertRow(tableLength);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML="col1";
col2.innerHTML="col2";
}
var delLink = document.getElementById("delete-link");
delLink.addEventListener('click',del,false);
function del()
{
var rowstoDelete = table.querySelectorAll("tbody tr");
[].slice.call(rowstoDelete).forEach(function(row) {
row.remove()
});
}
Below is a form when submitted displays the content in a table.
What works
Content is successfully transferred via form to table.
What is not working
I wanted to hide the table when the page loads and be displayed only after the form is submitted.
I tried #myTableData {visibility: hidden;} in css and then I tried plugging (.style.visibility="visible";) Javascript in my addtable function to display the table but it does not work. I am not sure if I am understanding this right.
Also how do I control the display of the table (like width, background color, font etc). I added (td.style.width = '200px'; but I don't see any changes).
CSS or JS for controlling table ?
function addTable() {
var table = document.createElement('TABLE').style.display = "block";
table.border='0';
for (var i=0; i<3; i++){
var tr = document.createElement('tr');
for (var j=0; j<4; j++){
var td = document.createElement('td');
td.style.width = '200px';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
}
function addRow() {
var myName = document.getElementById("name");
var domainName = document.getElementById("domain");
var url = document.getElementById("url");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(0).innerHTML= myName.value;
row.insertCell(1).innerHTML= domainName.value;
row.insertCell(2).innerHTML= url.value;
}
function load() {
console.log("Check if this loads");
}
/*
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
*/
#myTableData {visibility: hidden;}
body {
background: gray;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="table-app.js"></script>
<link rel="stylesheet" href="table-app.css">
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Domain</td>
<td><input type="text" id="domain">
</td>
</tr>
<tr>
<td>URL</td>
<td><input type="text" id="url"></td>
</tr>
<tr>
<td colspan=2><input type="button" id="add" value="Display as Table" onclick="Javascript:addRow()"></td>
</tr>
</table>
</div>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<th>Name</td>
<th>Domain</th>
<th>URL</th>
</tr>
</table>
</div>
<!--
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript
</div> -->
</body>
</html>
1) In function addRow add table.style.visibility = "visible"; ,to display the table, right after var table = document.getElementById("myTableData");.
2) To set styles like width you can can use setAttribute method.
document.getElementById('myTableData').setAttribute("style","width:200px");
Note: I can't see where you make use of addTable function, maybe this is why some of styles are not setted when you want.
function addTable() {
var table = document.createElement('TABLE').style.display = "block";
table.border='0';
for (var i=0; i<3; i++){
var tr = document.createElement('tr');
for (var j=0; j<4; j++){
var td = document.createElement('td');
td.style.width = '200px';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
}
function addRow() {
var myName = document.getElementById("name");
var domainName = document.getElementById("domain");
var url = document.getElementById("url");
var table = document.getElementById("myTableData");
table.style.visibility = "visible";
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(0).innerHTML= myName.value;
row.insertCell(1).innerHTML= domainName.value;
row.insertCell(2).innerHTML= url.value;
}
function load() {
console.log("Check if this loads");
}
/*
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
*/
#myTableData {visibility: hidden;}
body {
background: gray;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="table-app.js"></script>
<link rel="stylesheet" href="table-app.css">
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Domain</td>
<td><input type="text" id="domain">
</td>
</tr>
<tr>
<td>URL</td>
<td><input type="text" id="url"></td>
</tr>
<tr>
<td colspan=2><input type="button" id="add" value="Display as Table" onclick="Javascript:addRow()"></td>
</tr>
</table>
</div>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<th>Name</td>
<th>Domain</th>
<th>URL</th>
</tr>
</table>
</div>
<!--
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript
</div> -->
</body>
</html>
I don't have the rep to comment so I can't ask for details, but just in case you can use jquery, you can hide and show stuff like this:
$(function(){
$("#add").click(function() {
var name = $('#name').val();
var domain = $('#domain').val();
var url = $('#url').val();
$('#hidey').show();
$('#nametd').html(name);
$('#domtd').html(domain);
$('#urltd').html(url);
})
});
https://jsfiddle.net/6dxLsnL4/
Or trigger on form submit instead of click if you want, but there, you might want to consider ajax, because then you can make sure the form is processed on the server side before displaying the results.
I'm trying to create 2 dynamic html tables using Javascript with data from html inputs. I was able to create the first table I wanted but I've been unable to create 2 different tables using different inputs on the same page.
I tried changing the addRow() functions in the html and JS to have different names but this caused both tables to fail.
Any help would be appreciated. Here's the test code I've been using.
<!DOCTYPE html>
<body onload="load()">
<div id="myform">
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="number" id="age">
<input type="button" id="add" value="Add" onclick="addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<br>
<table>
<tr>
<td>Height:</td>
<td><input type="text" id="height"></td>
</tr>
<tr>
<td>Width:</td>
<td><input type="text" id="width">
<input type="button" id="addDim" value="Add" onclick="addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</div>
<div id="mydata">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Name</b></td>
<td><b>Age</b></td>
</tr>
</table>
<table id="myTableData2" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Height</b></td>
<td><b>Width</b></td>
</tr>
</table>
</body>
</html>
function addRow() {
var myName = document.getElementById("name");
var age = document.getElementById("age");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="deleteRow(this)">';
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
var width = document.getElementById("width");
var height = document.getElementById("height");
var table2 = document.getElementById("myTableData2");
var rowCount2 = table2.rows.length;
var row2 = table2.insertRow(rowCount2);
row.insertCell(0).innerHTML = '<input type="button" value="Delete" onClick="deleteRow(this)">';
row.insertCell(1).innerHTML = width.value;
row.insertCell(2).innerHTML = height.value;
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
function load() {
console.log("Page load finished");
}
Looks like in the bottom section, you're not using the row2 variable you've defined.
Should be:
var rowCount2 = table2.rows.length;
var row2 = table2.insertRow(rowCount2);
row2.insertCell(0).innerHTML = '<input type="button" value="Delete" onClick="deleteRow(this)">';
row2.insertCell(1).innerHTML = width.value;
row2.insertCell(2).innerHTML = height.value;
here how i did it. you can use the same function for any amount of table, if pass the parameter in the function.
http://jsfiddle.net/8t5aqomk/2/
function myFunction(thisTable) {
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var age = document.getElementById('age').value;
var info = [firstName,lastName,age]
var table = document.getElementById(thisTable);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cellCount = table.rows[0].cells.length;
for(var i=0; i<cellCount; i++) {
row.insertCell(i).innerHTML=info[i];
}
}