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

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

Make table via value

How do I do that JavaScript will print in my HTML page a table via the value the user will choose?
That the JS script:
let numCol = document.getElementById('txtColumns').value;
let numRow = document.getElementById('txtRows').value;
let go = document.getElementById('btn');
let table = document.getElementById('table');
let td = "<td></td>" * numCol;
let tr = ("<tr>" + td + "</tr>") * numRow;
go.addEventListener('click', function(){
table.innerHTML = tr;
})
That the HTML code:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<table class="workTable">
<tr>
<td>
<input type="number" placeholder="Columns Number" id="txtColumns">
</td>
<td>
<input type="number" placeholder="Rows Number" id="txtRows">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button id="btn">
Print
</button>
</td>
</tr>
<div>
<table id="table">
<!--Here I want to print the table-->
</table>
</div>
</table>
<script src="script.js"></script>
</body>
</html>
At first I thought about that way with the script but its only appear as a NaN and not table...
The following syntax:
let td = "<td></td>" * numCol;
does not produce numCol cells, so the following syntax:
let tr = ("<tr>" + td + "</tr>") * numRow;
does not produce numRow rows also.
So, the whole source code should be:
let go = document.getElementById('btn');
let table = document.getElementById('table');
go.addEventListener('click', () => {
let numCol = document.getElementById('txtColumns').value; //Get the value of txtColumns at the button click moment.
let numRow = document.getElementById('txtRows').value;
let td = "",
tr = "";
for (let i = 0; i < numCol; i++) {
td = td + "<td></td>";
}
for (let i = 0; i < numRow; i++) {
tr = tr + "<tr>" + td + "</tr>";
}
table.innerHTML = tr;
})
<table class="workTable">
<tr>
<td>
<input type="number" placeholder="Columns Number" id="txtColumns">
</td>
<td>
<input type="number" placeholder="Rows Number" id="txtRows">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button id="btn">
Print
</button>
</td>
</tr>
<div>
<table id="table" border="1">
<!--Here I want to print the table-->
</table>
</div>
</table>

My submited table does not show on the browser

I have a scoreboard where the user can enter the score and when the user presses the "Submit" button it will show a table that will contain the information that the user has entered. But when I try it in the browser, my table doesn't show the information that was entered in the previous form, it only show the table heading. Let me explain like below:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
var table = document.getElementById("tableScore");
var row = table.insertRow(i);
var number = row.insertCell(0);
var name = row.insertCell(1);
var math = row.insertCell(2);
var physics = row.insertCell(3);
var chemistry = row.insertCell(4);
var avg = row.insertCell(5);
number.innerHtml = i;
name.innerHtml = testScore.name;
math.innerHtml = testScore.math;
physics.innerHtml = testScore.physics;
chemistry.innerHtml = testScore.chemistry;
avg.innerHtml = testScore.avg;
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
In js code you have used innerHtml instead of innerHTML.
Updated code:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
var table = document.getElementById("tableScore");
var row = table.insertRow(i);
var number = row.insertCell(0);
var name = row.insertCell(1);
var math = row.insertCell(2);
var physics = row.insertCell(3);
var chemistry = row.insertCell(4);
var avg = row.insertCell(5);
number.innerHTML = i;
name.innerHTML = testScore.name;
math.innerHTML = testScore.math;
physics.innerHTML = testScore.physics;
chemistry.innerHTML = testScore.chemistry;
avg.innerHTML = testScore.avg;
i++;
}
#import url('https://fonts.googleapis.com/css2?family=Bree+Serif&family=Caveat:wght#400;700&family=Lobster&family=Monoton&family=Open+Sans:ital,wght#0,400;0,700;1,400;1,700&family=Playfair+Display+SC:ital,wght#0,400;0,700;1,700&family=Playfair+Display:ital,wght#0,400;0,700;1,700&family=Roboto:ital,wght#0,400;0,700;1,400;1,700&family=Source+Sans+Pro:ital,wght#0,400;0,700;1,700&family=Work+Sans:ital,wght#0,400;0,700;1,700&display=swap');
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
</body>
</html>
When you use insertCell you need to use innerHTML or appendChild instead of the non-existent innerHtml
Also you do not need to have any integer in insertCell/Row
Also your HTML was invalid
number.appendChild(document.createTextNode(i));
name.appendChild(document.createTextNode(testScore.name));
math.appendChild(document.createTextNode(testScore.math));
physics.appendChild(document.createTextNode(testScore.physics));
chemistry.appendChild(document.createTextNode(testScore.chemistry));
avg.appendChild(document.createTextNode(testScore.avg));
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physics = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
var table = document.querySelector("#tableScore tbody");
var row = table.insertRow();
var number = row.insertCell();
var name = row.insertCell();
var math = row.insertCell();
var physics = row.insertCell();
var chemistry = row.insertCell();
var avg = row.insertCell();
number.appendChild(document.createTextNode(i));
name.appendChild(document.createTextNode(testScore.name));
math.appendChild(document.createTextNode(testScore.math));
physics.appendChild(document.createTextNode(testScore.physics));
chemistry.appendChild(document.createTextNode(testScore.chemistry));
avg.innerHTML = testScore.avg; // alternative to appendChild
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table border="2" id="tableScore">
<thead>
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</thead>
<tbody>
</tbody>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
You have some misspelled variables but you can also minimize your output with only one global innerHTML like in my example below:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
//MINIMIZED VERSION
document.getElementById("tableScore").innerHTML +=
"<td>" + i + "</td>" +
"<td>" + testScore.name + "</td>" +
"<td>" + testScore.math + "</td>" +
"<td>" + testScore.physical + "</td>" +
"<td>" + testScore.chemistry + "</td>" +
"<td>" + testScore.avg + "</td>";
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>

Moving data from one html table to another

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>

Copy and paste from excel spreadsheet into HTML table with cloned rows using Javascript?

I have a table where the user can decide how many rows they wish to add. I've found a script that copy and pastes both columns and rows from excel. It works perfectly from the first 2 existing row's but the function doesn't work properly in any of the cloned rows that get added.
So if you use the function on the first two row's it will split the paste into each row and column (inluding the cloned rows) but if i try paste into a newly added row the function just doesn't work,
function cloneRow() {
var rowAmmount = document.getElementById("rowAmmount").value;
var getTotalRows = $('table > tbody').children().length;
for (var i = -1; i < rowAmmount-1;i++) {
var row = document.getElementById("row"); // find row to copy
var table = document.getElementById("table"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newRow" + (getTotalRows + i); // change id or other attributes/contents
clone.classList.remove('hidden');
table.appendChild(clone); // add new row to end of table
$('#newRow' + (getTotalRows + i)).children().each(function() {
$(this).children().attr('id', $(this).children().attr('id') + (getTotalRows + i));
});
}}
$('input').on('paste', function(e){
var $this = $(this);
$.each(e.originalEvent.clipboardData.items, function(i, v){
if (v.type === 'text/plain'){
v.getAsString(function(text){
var x = $this.closest('td').index(),
y = $this.closest('tr').index()+1,
obj = {};
text = text.trim('\r\n');
$.each(text.split('\r\n'), function(i2, v2){
$.each(v2.split('\t'), function(i3, v3){
var row = y+i2, col = x+i3;
obj['cell-'+row+'-'+col] = v3;
$this.closest('table').find('tr:eq('+row+') td:eq('+col+') input').val(v3);
});
});
});
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="rowAmmount"/>
<button id="add" onclick="cloneRow()">New Row</button>
<button type="button" onclick="submit()">Submit</button>
<table>
<thead>
<tr>
<th>Product Code</th>
<th>Item Name</th>
<th>Long Description></th>
<th>Material</th>
<th>Style</th>
</tr>
</thead>
<tbody id="table">
<tr id="row">
<td><input id="productId"></td>
<td><input id="itemname"></td>
<td><input id="long"></td>
<td><input id="fabric"></td>
<td><input id="style"></td>
</tr>
<tr id= "newRow0">
<td><input id="productId0"></td>
<td><input id="itemname0"></td>
<td><input id="long0"></td>
<td><input id="fabric0"></td>
<td><input id="style0"></td>
</tr>
</tbody>
</table>
You attach the change event handler before you insert the new inputs.
What you need is delegated event handling $('table').on('paste', 'input', function(e){
function cloneRow() {
var rowAmmount = document.getElementById("rowAmmount").value;
var getTotalRows = $('table > tbody').children().length;
for (var i = -1; i < rowAmmount-1;i++) {
var row = document.getElementById("row"); // find row to copy
var table = document.getElementById("table"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newRow" + (getTotalRows + i); // change id or other attributes/contents
clone.classList.remove('hidden');
table.appendChild(clone); // add new row to end of table
$('#newRow' + (getTotalRows + i)).children().each(function() {
$(this).children().attr('id', $(this).children().attr('id') + (getTotalRows + i));
});
}}
$('table').on('paste', 'input', function(e){
var $this = $(this);
$.each(e.originalEvent.clipboardData.items, function(i, v){
if (v.type === 'text/plain'){
v.getAsString(function(text){
var x = $this.closest('td').index(),
y = $this.closest('tr').index()+1,
obj = {};
text = text.trim('\r\n');
$.each(text.split('\r\n'), function(i2, v2){
$.each(v2.split('\t'), function(i3, v3){
var row = y+i2, col = x+i3;
obj['cell-'+row+'-'+col] = v3;
$this.closest('table').find('tr:eq('+row+') td:eq('+col+') input').val(v3);
});
});
});
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="rowAmmount"/>
<button id="add" onclick="cloneRow()">New Row</button>
<button type="button" onclick="submit()">Submit</button>
<table>
<thead>
<tr>
<th>Product Code</th>
<th>Item Name</th>
<th>Long Description></th>
<th>Material</th>
<th>Style</th>
</tr>
</thead>
<tbody id="table">
<tr id="row">
<td><input id="productId"></td>
<td><input id="itemname"></td>
<td><input id="long"></td>
<td><input id="fabric"></td>
<td><input id="style"></td>
</tr>
<tr id= "newRow0">
<td><input id="productId0"></td>
<td><input id="itemname0"></td>
<td><input id="long0"></td>
<td><input id="fabric0"></td>
<td><input id="style0"></td>
</tr>
</tbody>
</table>

Uncaught SyntaxError: Unexpected string in my Javascript code

I keep getting this error in my code and I don't understand why. See line 29 of my Javascript.
HTML
<link href="Styles12.css"; type="text/css" rel="stylesheet">
<link rel="stylesheet" href="Styles12.css"/>
<script src="registration.js"></script>
<body onload="studentAttendance()">
<head>
<style>
table, td, th {
border: 1px solid black;
}
th {
background-color: beige;
color:black;
}
</style>
</head>
<h3 style= "font-size:25px; font-family:Impact"> ADD A STUDENT</h3>
Firstname:
Lastname:
Student number:
<button onclick = "save()"><p>+ADD TO ATTENDANCE</a></p> </button>
<h2 style="font-size: 25px;font-family: Impact">Online attendance</h2>
<table id= "attendanceTable">
<table border="10px">
<thead>
<tr>
<th> Student Name </th>
<th> Student Number </th>
<th> A </th>
<th> Points </th>
<th style="font-size:10px;font-align: left"><em><button> Edit:Add student(+)</a></button></em></th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td><form action="demo_form.asp" method="get"></form></td>
<td></td>
<td> <input type="button" value="save"></input>
<button>reset</button></td>
</tr>
<tbody>
<tr>
<td></td>
<td></td>
<td><form action="demo_form.asp" method="get"></form></td>
<td></td>
</tr>
<tbody>
<tr>
<td></td>
<td></td>
<td><form action="demo_form.asp" method="get"></form></td>
<td></td>
</tr>
</tbody>
</table>
<form>
</form>
<button type="button" onlick="alert('Attendence submitted')"> <strong>SUBMIT</strong></button>
<p id="demo"></p>
</body>
JAVASCRIPT
var studentNo = [];
var index = 0;
var studentInfo = [];
var newObj = [];
function save() { //this function takes values from the text box and stores them as an object studentInfo[index] = { studentNumber: document.getElementById("studentNo").value, firstname: document.getElementById("firstname").value, lastname: document.getElementById("lastname").value, }; index++;
localStorage.setItem("studentRecord", JSON.stringify(studentInfo));
}
function studentAttendance() {
newObj = JSON.parse(localStorage.getItem("studentRecord"));
var table, row, cell1, cell2, cell3;
table = document.getElementById("onlineAttendance");
studentInfo = JSON.parse(localStorage.getItem("studentRecord"));
for (var index = 0; index < studentInfo.length; index++) {
row = table.insertRow(index + 1);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell1.innerHTML = studentInfo[index].studentNumber;
cell2.innerHTML = studentInfo[index].firstName + " " +
studentInfo[index].lastName;
cell3.innerHTML = studentInfo[index].
'<input type="checkbox" name="student attendance" value="absent" id="checkboxab"</input>';
}
function save() {
if (document.getElementById('checkboxab').checked) {
alert("checked");
} else {
alert("You didnt check it")
studentInfo.points++
}
}
}
. use in php to concat string
+ use in javascript to concat string
try like this
cell3.innerHTML =studentInfo[index]+
'<input type="checkbox" name="student attendance" value="absent" id="checkboxab"</input>';
I think that you are confusing PHP string concatenating with Javascript string concatenating:
PHP
$variable = $other_variable . '<span>hello world</span>'
Javascript
var variable = other_variable + '<span>hello world</span>'
I get it?
The dot is a syntax error. You should use a +.
cell3.innerHTML = studentInfo[index].
'<input type="checkbox" name="student attendance" value="absent" id="checkboxab"</input>';
If you don't have another way to validate your JS, put it into a jsfiddle and press JSHint.
http://jsfiddle.net/mgb8x7pd/

Categories

Resources