Make table via value - javascript

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>

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

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>

Sum up cell values in HTML table if checkbox is checked

I have a table with three columns: item, price and a checkbox. I want to calculate the subtotal but only include the prices with a checked checkbox. The code I have so far is a mix of various bits that work on its own; however right now I get the error message "TypeError: Cannot read properties of undefined (reading 'innerHTML')". What am I doing wrong?
function calculate() {
const ele = document.getElementsByTagName('input');
let table = document.getElementById("myTable");
let tr = table.getElementsByTagName("tr");
let subTotal = 0;
for (var i = 0; i < ele.length; i++) {
let td = tr[i].getElementsByTagName("td")[1];
let price = td[i].innerHTML;
if (ele[i].type == 'checkbox' && ele[i].checked == true)
subTotal += price;
}
document.getElementById("val").innerHTML = "The subtotal is " + subTotal;
}
<!DOCTYPE html>
<html>
<body>
<table id="myTable">
<tr>
<td>T-Shirt</td>
<td>9.99</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td>Pants</td>
<td>49.99</td>
<td><input type="checkbox"></td>
</tr>
</table>
<span id="val">The subtotal is 0</span>
<button onclick="calculate()">Calculate subtotal</button>
</html>
You have to change the line td[i] because it's not defined as the error suggests. So, consider using bare td and accessing its innerText. It'll return a string with the value, which you have to convert to a float number with parseFloat. Finally, you must set the precision you want to subTotal so that it will print with the number of decimals you want.
function calculate() {
const ele = document.getElementsByTagName('input');
let table = document.getElementById("myTable");
let tr = table.getElementsByTagName("tr");
let subTotal = 0;
for (var i = 0; i < ele.length; i++) {
let td = tr[i].getElementsByTagName("td")[1];
let price = parseFloat(td.innerText); // change here
if (ele[i].type == 'checkbox' && ele[i].checked == true)
subTotal += price;
}
document.getElementById("val").innerHTML = "The subtotal is " + subTotal.toFixed(2); // and set precision here
}
<!DOCTYPE html>
<html>
<body>
<table id="myTable">
<tr>
<td>T-Shirt</td>
<td>9.99</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td>Pants</td>
<td>49.99</td>
<td><input type="checkbox"></td>
</tr>
</table>
<span id="val">The subtotal is: </span>
<button onclick="calculate()">Calculate subtotal</button>
</html>
Problem with your code is simple. You referenced the td and than you try to reference it again.
let td = tr[i].getElementsByTagName("td")[1];
let price = td[i].innerHTML;
Should be
const td = tr[i].getElementsByTagName("td")[1];
const price = td.innerHTML;
If you use a value on the checkbox, you can just loop over the checked inputs and calculate the total using the values. No need to look up cell contents.
function calculate() {
const checkedInputs = document.querySelectorAll("#myTable input:checked");
const total = Array.from(checkedInputs).reduce(function(total, cb) {
return total + +cb.value;
}, 0);
document.querySelector("#val").textContent = "The subtotal is " + total.toFixed(2);
}
<table id="myTable">
<tr>
<td>T-Shirt</td>
<td>9.99</td>
<td><input type="checkbox" value="9.99"></td>
</tr>
<tr>
<td>Pants</td>
<td>49.99</td>
<td><input type="checkbox" value="49.99"></td>
</tr>
</table>
<span id="val">The subtotal is 0</span>
<button onclick="calculate()">Calculate subtotal</button>
You can iterate trhough checkbox and going up until the previous td
function calculate() {
let chckboxes = document.querySelectorAll('#myTable input:checked');
let sum = 0;
chckboxes.forEach((itm) => {
let val = parseFloat(itm.parentElement.previousElementSibling.innerHTML)
sum += val;
});
document.getElementById("val").innerHTML = "The subtotal is " + sum;
}
<!DOCTYPE html>
<html>
<body>
<table id="myTable">
<tr>
<td>T-Shirt</td>
<td>9.99</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td>Pants</td>
<td>49.99</td>
<td><input type="checkbox"></td>
</tr>
</table>
<span id="val">The subtotal is 0</span>
<button onclick="javascript:calculate()">Calculate subtotal</button>
</html>

calculating row and column operations dynamically in a table in a html form

A billing form
I am trying to make a billing form where I need to automatically show amount generated after entering values for price and quantity columns. But with the following code I am only able to calculate it for one row. I want it to work for every row each time I entry values to it and at the end, it should display sum total of the amount column also.
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('billingSheet').deleteRow(i);
}
function addRow(){
var x=document.getElementById('billingSheet');
// deep clone the targeted row
var new_row = x.rows[1].cloneNode(true);
// get the total number of rows
var len = x.rows.length;
// set the innerHTML of the first row
new_row.cells[0].innerHTML = len;
// grab the input from the first cell and update its ID and value
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
// grab the input from the second cell and update its ID and value
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
// grab the input from the third cell and update its ID and value
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = '';
// append the new row to the table
x.appendChild( new_row );
}
function calc(){
$('#input1,#input2').keyup(function(){
var textValue1 =$('#input1').val();
var textValue2 = $('#input2').val();
$('#output').val(textValue1 * textValue2);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="billingSheet" border="1" width="65%">
<tr>
<th>Serial No</th>
<th>Enter item name</th>
<th> Price </th>
<th> Quantity </th>
<th> Amount</th>
<th>Add</th>
<th>Delete</th>
</tr>
<tr>
<td>1</td>
<td><input type="text"></td>
<td><input type="number" name="input1" id="input1" onkeyup="calc()"></td>
<td><input type="number" name="input2" id="input2" onkeyup="calc()"></td>
<td><input type="text" name="output" id="output" value=""></td>
<td><input type="button" id="add" value="Add Row" onClick="addRow()"/></td>
<td><input type="button" id="delete" value="Delete Row" onclick="deleteRow(this)"></td>
</tr>
</table>
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('billingSheet').deleteRow(i);
}
var input1 = "";
function addRow() {
var x = document.getElementById('billingSheet');
// deep clone the targeted row
var new_row = x.rows[1].cloneNode(true);
// get the total number of rows
var len = x.rows.length;
// set the innerHTML of the first row
new_row.cells[0].innerHTML = len;
// grab the input from the first cell and update its ID and value
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
// grab the input from the second cell and update its ID and value
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.name = len;
inp2.value = '';
// grab the input from the third cell and update its ID and value
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.id += len;
inp3.name = len;
inp3.value = '';
// grab the input from the third cell and update its ID and value
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.id = "output" + len;
inp4.value = '';
// append the new row to the table
x.appendChild(new_row);
}
function calc(input, name) {
if (!input.value || isNaN(input.value))
return;
var str = input.id.substr(6, input.id.length);
var textValue1 = $('#input1' + str).val();
var textValue2 = $('#input2' + str).val();
$('#output' + name).val(textValue1 * textValue2);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="billingSheet" border="1" width="65%">
<tr>
<th>Serial No</th>
<th>Enter item name</th>
<th> Price </th>
<th> Quantity </th>
<th> Amount</th>
<th>Add</th>
<th>Delete</th>
</tr>
<tr>
<td>1</td>
<td><input type="text"></td>
<td><input type="number" name ="1" id="input1" onkeyup="calc(this,name)"></td>
<td><input type="number" name ="1" id="input2" onkeyup="calc(this,name)"></td>
<td><input type="text" name="output1" id="output1" value=""></td>
<td><input type="button" id="add" value="Add Row" onClick="addRow()"/></td>
<td><input type="button" id="delete" value="Delete Row" onclick="deleteRow(this)"></td>
</tr>
</table>
</body>
<script src="js/index.js"></script>
</html>

How to UNDO the added row(s) WITHOUT DELETING the table heading

Right now, i have a reset button to reset all rows that have been added. The problem is it also deletes my table heading which i want to keep.
Any ideas to keep the table heading?Thanks guys.
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of injection');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = ` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" style="width: 100px" name="vaccineid[]"></td>
<td><input type="text" style="width:160px"name="vaccinename1[]"> </td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
$('[name="reset"]').click(function() {
$('#one tr').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Add Row</button>
<button type="reset" name="reset">Reset Row</button>
<table id="one">
<thead>
<th>No.</th>
<th>Name</th>
<th>Gender</th>
</thead>
<tbody>
</tbody>
</table>
Just select <TBODY>
$('#one tbody tr').remove();

Categories

Resources