Moving data from one html table to another - javascript

I am struggling with something that should be so simple.
I am trying to move a row from one html table to another, basically a table with selection options and input to another table with the final selections and values.
Image for UI
My Html code is as follow,
function GetIndex()
{
var table = document.getElementById("table1");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
console.log("HERE " + id );
localStorage.setItem("ID", id);
};
};
currentRow.onclick = createClickHandler(currentRow);
AddNextTable();
}
}
function AddNextTable()
{
var ID= localStorage.getItem("ID");
var table1 = document.getElementById("table1"),
table2 = document.getElementById("table2");
var table = document.getElementById("table1");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
var Counter= 0;
Counter++;
var InputSelect= "input" + ID;
console.log(InputSelect);
var NewText= document.getElementById(InputSelect).value;
var newRow = table2.insertRow(table2.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3);
cell1.innerHTML = table1.rows[id].cells[0].innerHTML;
cell2.innerHTML = table1.rows[id].cells[1].innerHTML;
cell3.innerHTML = table1.rows[id].cells[2].innerHTML;
cell4.innerHTML = "<input type='checkbox' name='check-tab2'>";
cell3.innerHTML= "<input type='text' value="+ NewText+ ">"
var index = table1.rows[1].rowIndex;
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
function tab2_To_tab1()
{
var table1 = document.getElementById("table1"),
table2 = document.getElementById("table2"),
checkboxes = document.getElementsByName("check-tab2");
console.log("Val1 = " + checkboxes.length);
for(var i = 0; i < checkboxes.length; i++)
if(checkboxes[i].checked)
{
// create new row and cells
var newRow = table1.insertRow(table1.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3);
// add values to the cells
cell1.innerHTML = table2.rows[i+1].cells[0].innerHTML;
cell2.innerHTML = table2.rows[i+1].cells[1].innerHTML;
cell3.innerHTML = table2.rows[i+1].cells[2].innerHTML;
cell4.innerHTML = "<input type='checkbox' name='check-tab1'>";
// remove the transfered rows from the second table [table2]
var index = table2.rows[i+1].rowIndex;
table2.deleteRow(index);
// we have deleted some rows so the checkboxes.length have changed
// so we have to decrement the value of i
i--;
console.log(checkboxes.length);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Transfer Rows Between Two HTML Table</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container{overflow: hidden}
.tab{float: left}
.tab-btn{margin: 50px;}
button{display:block;margin-bottom: 20px;}
tr{transition:all .25s ease-in-out}
tr:hover{background-color: #ddd;}
</style>
</head>
<body>
<div class="container">
<div class="tab">
<table id="table1" border="1">
<tr>
<th>Code</th>
<th>Name</th>
<th>Amount</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>
<input type="text" id="input1">
</td>
<td>
<button onclick="GetIndex()">Add</button>
</td>
</tr>
<tr>
<td>2</td>
<td>Dean</td>
<td><input type="text" id="input2"></td>
<td>
<button onclick="GetIndex()">Add</button>
</td>
</tr>
<tr>
<td>3</td>
<td>Fred</td>
<td><input type="text" id="input3"></td>
<td>
<button onclick="GetIndex()">Add</button>
</td>
</tr>
</table>
</div>
<div class="tab">
<table id="table2" border="1">
<tr>
<th>Code</th>
<th>Name</th>
<th>Action</th>
<th>Action</th>
</tr>
</table>
</div>
</div>
</body>
<script src="main.js"></script>
</html>
My end goal will be for the user to enter a certain amount of an item in the first table, and have it display in the next. I am looping through something incorrectly somewhere.

I found it quite complicated about your code. Just why not giving it a param that describes which button/input called the function? It will be much easier and also this will no longer require the use of localStorage. Hope this solves your problem.
On the html:
<button onclick="GetIndex('input1')"></button>
On the js
function GetIndex(src) {
...
AddIndex(src);
...
}
function AddIndex(src) {
...
var ID = src;
...
}
function GetIndex(src)
{
var table = document.getElementById("table1");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
console.log("HERE " + id );
localStorage.setItem("ID", id);
};
};
currentRow.onclick = createClickHandler(currentRow);
AddNextTable(src);
}
}
function AddNextTable(src)
{
var table1 = document.getElementById("table1"),
table2 = document.getElementById("table2");
var table = document.getElementById("table1");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
var Counter= 0;
Counter++;
var InputSelect= src;
console.log(InputSelect);
var NewText= document.getElementById(InputSelect).value;
var newRow = table2.insertRow(table2.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3);
cell1.innerHTML = table1.rows[id].cells[0].innerHTML;
cell2.innerHTML = table1.rows[id].cells[1].innerHTML;
cell3.innerHTML = table1.rows[id].cells[2].innerHTML;
cell4.innerHTML = "<input type='checkbox' name='check-tab2'>";
cell3.innerHTML= "<input type='text' value="+ NewText+ ">"
var index = table1.rows[1].rowIndex;
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
function tab2_To_tab1()
{
var table1 = document.getElementById("table1"),
table2 = document.getElementById("table2"),
checkboxes = document.getElementsByName("check-tab2");
console.log("Val1 = " + checkboxes.length);
for(var i = 0; i < checkboxes.length; i++)
if(checkboxes[i].checked)
{
// create new row and cells
var newRow = table1.insertRow(table1.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3);
// add values to the cells
cell1.innerHTML = table2.rows[i+1].cells[0].innerHTML;
cell2.innerHTML = table2.rows[i+1].cells[1].innerHTML;
cell3.innerHTML = table2.rows[i+1].cells[2].innerHTML;
cell4.innerHTML = "<input type='checkbox' name='check-tab1'>";
// remove the transfered rows from the second table [table2]
var index = table2.rows[i+1].rowIndex;
table2.deleteRow(index);
// we have deleted some rows so the checkboxes.length have changed
// so we have to decrement the value of i
i--;
console.log(checkboxes.length);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Transfer Rows Between Two HTML Table</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container{overflow: hidden}
.tab{float: left}
.tab-btn{margin: 50px;}
button{display:block;margin-bottom: 20px;}
tr{transition:all .25s ease-in-out}
tr:hover{background-color: #ddd;}
</style>
</head>
<body>
<div class="container">
<div class="tab">
<table id="table1" border="1">
<tr>
<th>Code</th>
<th>Name</th>
<th>Amount</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>
<input type="text" id="input1">
</td>
<td>
<button onclick="GetIndex('input1')">Add</button>
</td>
</tr>
<tr>
<td>2</td>
<td>Dean</td>
<td><input type="text" id="input2"></td>
<td>
<button onclick="GetIndex('input2')">Add</button>
</td>
</tr>
<tr>
<td>3</td>
<td>Fred</td>
<td><input type="text" id="input3"></td>
<td>
<button onclick="GetIndex('input3')">Add</button>
</td>
</tr>
</table>
</div>
<div class="tab">
<table id="table2" border="1">
<tr>
<th>Code</th>
<th>Name</th>
<th>Action</th>
<th>Action</th>
</tr>
</table>
</div>
</div>
</body>
<script src="main.js"></script>
</html>

I think you're overcomplicating.
You don't need localStorage, you don't need almost anything. Just a bit of JS .append() to move back and forth your rows. Than using CSS you can additionally pimp the desired items to show/hide or even the button text:
const moveTR = (ev) => {
const EL_tr = ev.currentTarget.closest("tr");
const sel = EL_tr.closest("table").id === "table1" ? "#table2" : "#table1";
document.querySelector(sel + " tbody").append(EL_tr);
};
document.querySelectorAll("table button")
.forEach(EL => EL.addEventListener("click", moveTR));
table {border-collapse: collapse;}
th, td {border: 1px solid #ddd; padding: 5px 10px;}
#table1 button::after {content: "Add"}
#table2 button::after {content: "\2715"}
<table id="table1">
<thead>
<tr><th>Code</th><th>Name</th><th>Amount</th><th>Action</th></tr>
</thead>
<tbody>
<tr>
<td>8</td><td>Fred</td><td><input type="text"></td>
<td><button type="button"></button></td>
</tr>
<tr>
<td>4</td><td>Dean</td><td><input type="text"></td>
<td><button type="button"></button></td>
</tr>
<tr>
<td>1</td><td>Mark</td><td><input type="text"></td>
<td><button type="button"></button></td>
</tr>
</tbody>
</table>
<table id="table2">
<thead>
<tr><th>Code</th><th>Name</th><th>Amount</th><th>Action</th></tr>
</thead>
<tbody>
</tbody>
</table>

Related

How to show JSON response in datatable using JavaScript [duplicate]

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);

adding bootstrap collapse to table cell with rowspan

I am creating a table using html, bootstrap and js.
I have used rowspan to get cells of different height.
The third cell in each row has more rows than the rest of the cells(hence the rowspan) (If this line is not clear please take a look at the jsfiddle)
Now each of the row in the third cell is a collapsible. So when I click on row it should open another table. (I have just made the first row collapsible for simplicity)
I have 2 issues:
1) The width of the cell increases when I click the collapsible element and decreases when I hide the collapsible element. I want the width to remain the same.
2) I want to make the hidden table start from the same place as the outer tables. It currently starts somewhere randomly on the page
$(document).ready(function() {
var list1 = {
"Feature": "TestSuite",
"Scenario": "TestName",
"Step": "line1<br>line2<br>line3<br>line4<br>",
"Result": "PASS"
}
var list2 = {
"Feature": "TestSuite1",
"Scenario": "TestName1",
"Step": "line1.1<br>line2.1<br>line3.1<br>line4.1<br>",
"Result": "PASS"
}
var dashboardMap = {
"TestSuite1": [list1, list2],
}
for (var key in dashboardMap) {
var resultsTable = dashboardMap[key];
for (var i in resultsTable) {
table = document.getElementById("resultsTable");
row = table.insertRow(-1);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell1.innerHTML = "N/A";
cell2.innerHTML = resultsTable[i].Scenario;
var list = resultsTable[i].Step.split("<br>");
var rowspan = 0;
list.splice(-1, 1);
for (var step in list) {
rowspan++;
}
cell1.rowSpan = rowspan;
cell2.rowSpan = rowspan;
cell4.rowSpan = rowspan;
var hiddenTable = '<table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td>Alfreds</td> <td>Maria</td> <td>Germany</td> </tr> <tr>'
cell3.innerHTML = '<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#demo">Simple collapsible</button><i id="demo" class="collapse"> ' + hiddenTable + ' </i>'
cell4.innerHTML = resultsTable[i].Result;
var k;
for (k = 1; k < list.length; k++) {
row = table.insertRow(-1);
cell1 = row.insertCell(0);
cell1.innerHTML = list[k];
}
}
}
});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<div id="temp" class="container">
<div class="table-responsive">
<table class="table table-striped" id="resultsTable">
<thead>
<tr class="highlight-header" rowspan="3">
<th>header 1</th>
<th>header 2</th>
<th>header 3</th>
<th>header 4</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>

Adding elements with JavaScript

I want to add a new row to a table. Therefore I have tried it in two different ways. In my opinion both should work. But indeed the don't. The first approach does not work. But why?
First approach (not working...):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Table</title>
<script type="text/javascript">
function addLine(nr, name, date) {
var neueZeile = document.createElement("tr");
var neuerEintrag1 = document.createElement("td");
var neuerText1 = document.createTextNode(nr);
var neuerEintrag2 = document.createElement("td");
var neuerText2 = document.createTextNode(name);
var neuerEintrag3 = document.createElement("td");
var neuerText3 = document.createTextNode(date);
neuerEintrag1.appendChild(neuerText1);
neuerEintrag2.appendChild(neuerText2);
neuerEintrag3.appendChild(neuerText3);
neueZeile.appendChild(neuerEintrag1);
neueZeile.appendChild(neuerEintrag2);
neueZeile.appendChild(neuerEintrag3);
var parentN = document.getElementById("myTable");
parentN.appendChild(neueZeile);
</script>
<link rel="stylesheet" type="text/css" href="Website.css" />
</head>
<body>
<table class="table" id="myTable">
<thead>
<td>Nr.</td>
<td>Name</td>
<td>Datum</td>
</thead>
<tr>
<td>1</td>
<td>Max</td>
<td>01.01.2001</td>
</tr>
</table>
<form name=addRow>
Nr.:
<input type=text name=btn1>
Name:
<input type=text name=btn2>
Date:
<input type=text name=btn3>
<input type=button name=btn4 value=ADD
onclick="addLine(btn1.value,btn2.value,btn3.value)">
</form>
<input type=button name=btn5 value=DeleteLastAddedRow onclick="deleteRow()">
<a class="back" href="Website.html">Zurück</a>
</body>
</html>
My approach is not working. Does somebody know why or can help me?
Second approach (works fine...):
function addLine(nr, name, date) {
var table = document.getElementById("myTable");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = nr;
cell2.innerHTML = name;
cell3.innerHTML = date;
}
I am really interested in why the the first approach is not working.
Does somebody have an idea?
Kind regards
You missed to create tr element. Create tr and append it to table then all td to new tr.
Here is working code
function addLine(nr, name, date) {
var neuerEintrag1 = document.createElement("td");
var neuerText1 = document.createTextNode(nr);
var neuerEintrag2 = document.createElement("td");
var neuerText2 = document.createTextNode(name);
var neuerEintrag3 = document.createElement("td");
var neuerText3 = document.createTextNode(date);
neuerEintrag1.appendChild(neuerText1);
neuerEintrag2.appendChild(neuerText2);
neuerEintrag3.appendChild(neuerText3);
var parentN = document.getElementById("myTable");
var row = document.createElement("tr");
parentN.appendChild(row);
row.appendChild(neuerEintrag1);
row.appendChild(neuerEintrag2);
row.appendChild(neuerEintrag3);
}
<table class="table" id="myTable">
<thead>
<td>Nr.</td>
<td>Name</td>
<td>Datum</td>
</thead>
<tr>
<td>1</td>
<td>Max</td>
<td>01.01.2001</td>
</tr>
</table>
<form name=addRow>
Nr.:
<input type=text name=btn1> Name:
<input type=text name=btn2> Date:
<input type=text name=btn3>
<input type=button name=btn4 value=ADD onclick="addLine(btn1.value,btn2.value,btn3.value)">
</form>

How to add a button that will make calculations from a table using Javascript

I have been trying to add both a row and a column to a table, which I think I have finally managed. Now I am trying to create a button using javascript beneath the table that will calculate the sum of each row in the new column and will calculate the the last two columns in the new row. I have tried various ways of creating the button but I can't seem to make it work, and as you can see I don't know how to create the code that will make the calculations that I need.
Here is my code:
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
}
else
{
window.onload = function()
{
oldonload();
func();
}
}
}
function addRow()
{
if (!document.getElementById) return false;
var table = document.getElementById("pricetable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.setAttribute("id","sumrow");
var cell1 = row.insertCell();
var cell2 = row.insertCell();
var cell3 = row.insertCell();
var cell4 = row.insertCell();
var cell5 = row.insertCell();
}
function addColumn()
{
if (!document.getElementById) return false;
if (!document.createElement) return false;
var tHead = document.getElementById("pricetable").tHead;
for (var h=0; h<tHead.rows.length; h++)
{
var newTHead = document.createElement("th");
tHead.rows[h].appendChild(newTHead);
newTHead.innerHTML = "Sum";
}
var tBody = document.getElementById("pricetable").tBodies[0];
for (var i=0; i<tBody.rows.length; i++)
{
var newCell = tBody.rows[i].insertCell(-1);
}
}
function addButton()
{
var btn = document.createElement("input");
input.setAttribute("type", "button");
input.setAttribute("name","Calc price");
var foo = document.getElementById("pricetable");
foo.appendChild(btn);
btn.onclick = function()
{
alert ("Calulate price");
}
}
addLoadEvent(addRow);
addLoadEvent(addColumn);
addLoadEvent(addButton);
Here is the HTML code:
<body>
<div id ="container">
<div id ="header">
<h1>Electronics</h1>
</div>
<div id ="content">
<h3>Our prices</h3>
<table id ="pricetable">
<thead>
<tr>
<th>Article</th>
<th>Type</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>23456789</td>
<td>Phone</td>
<td>Apple</td>
<td>6500</td>
<td><input type ="text" size ="3" value ="1"/></td>
</tr>
<tr>
<td>22256289</td>
<td>Phone</td>
<td>Samsung</td>
<td>6200</td>
<td><input type ="text" size ="3" value ="1"/></td>
</tr>
<tr>
<td>24444343</td>
<td>Phone</td>
<td>MS Lumia</td>
<td>4200</td>
<td><input type ="text" size ="3" value ="1"/></td>
</tr>
<tr>
<td>19856639</td>
<td>Tablet</td>
<td>LG</td>
<td>4000</td>
<td><input type ="text" size ="3" value ="1"/></td>
</tr>
<tr>
<td>39856639</td>
<td>Tablet</td>
<td>Dell</td>
<td>2800</td>
<td><input type ="text" size ="3" value ="1"/></td>
</tr>
<tr>
<td>12349862</td>
<td>Tablet</td>
<td>Apple</td>
<td>3500</td>
<td><input type ="text" size ="3" value ="1"/></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>

How to insert row with attributes using table.insertRow?

I have a html table and insert a new row with table.insertRow(), but the new row doesn't have any attributes or formatting applied. How can I add a row to the table with row formatting?
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="100%" align="center">
<TR align="center" border="1">
<TH></TH>
<TH>ID </TH>
<TH>Name</TH>
<TH>Status</TH>
</TR>
<TR align="center">
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD> 1 </TD>
<TD> <INPUT type="text" value="Submission 1" /> </TD>
<TD>Working version</TD>
</TR>
</TABLE>
<script type="text/javascript">
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";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
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--;
}
}
}catch(e) {
alert(e);
}
}
</script>
I found it's better to use jquery to add rows to tables
$('#dataTable tr:last').after('<TR align="center"><TD><INPUT type="checkbox" name="chk"/></TD><TD>'+ rowCount + '</TD><TD> <INPUT type="text" value="Submission 1" /> </TD><TD>Working version</TD></TR>');
To set the class name for a tablerow you simply need to edit the className attribute as done below
<script>
var table = document.getElementById("tableID");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount-1);
row.className = "rowdiv";
</script>
Considering insertRow() is usually where you put the index, and var row = table.insertRow(rowCount); is used here, how can you move it to specific part of the table?

Categories

Resources