How to add dynamic value to dynamic generated table using javascript - javascript

I am making an EMI calculator where I want to calculate monthly installments and a table for each installment. You can see the result when you put the interest rate [example 9].
My question is how can I generate that table with some calculated value so each column will decrease the value from the principal. Like ai added an Image
here is an example: https://codepen.io/exclutips/pen/ZEvgXvb
function addTable(installment,amount,rate) {
var table = document.querySelector("DynamicTable");
var tableBody = document.getElementById('DynamicTable').getElementsByTagName('tbody')[0];
tableBody.innerHTML = "";
for (var i = 1; i < installment+1; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 1; j < 8 + 1; j++) {
var td = document.createElement('TD');
if(i <=12){
td.appendChild(document.createTextNode(amount));
tr.appendChild(td);
}
if(i > 12){
td.appendChild(document.createTextNode(rate));
tr.appendChild(td);
}
}
}
}
function Calculate() {
// Extracting value in the amount
var amount = document.querySelector("#loanAmount").value;
var rateValue = document.querySelector("#interestRate").value;
var year = document.querySelector("#loanPeriod").value;
var gracePeriod = document.querySelector("#gracePeriod").value;
var paymentperyear = document.querySelector("#paymentPerYear").value;
var instalment = document.querySelector("#instalment").value;
var graceInstalment = document.querySelector("#graceInstalment").value;
var payableTotalInt = document.querySelector("#payableTotal").value;
var principalMonthly = document.querySelector("#principalMonthly").value;
var interestMonthly = document.querySelector("#interestMonthly").value;
var interestEmployee = document.querySelector("#interestEmployee").value;
var govtSubsidy = document.querySelector("#govtSubsidy").value;
var employeeMonth = document.querySelector("#employeeMonth").value;
const rate = rateValue / 100;
//calculate months /
const months = year * paymentperyear;
//Number of instalment
const instalment_g = months - gracePeriod;
//Number of instalment with grace
const installmentGrace = year * paymentperyear;
// Calculating Payable Total interest
const interest = ((amount * rate) * (instalment_g + 1) / (paymentperyear * 2) + (amount * rate * gracePeriod) / paymentperyear);
//monthly payable Principal
const month_pay_principal = amount / instalment_g;
//monthly payable interest
const month_pay_interest = interest / instalment_g;
//Monthly Payable Interest by Employee
const month_pay_interest_emp = month_pay_interest * 4 / 9;
//Monthly Interest Subsidy by Govt.
const month_subsidy_interest_govt = month_pay_interest * 5 / 9;
//instalment for employee
const instalment_for_employee = month_pay_principal + month_pay_interest_emp;
//instalment for employee
const emi = month_pay_principal + month_pay_interest;
document.querySelector("#instalment").value = instalment_g;
document.querySelector("#graceInstalment").value = months;
//-----------------------------------------------------------
document.querySelector("#payableTotal").value = Math.round(interest);
document.querySelector("#principalMonthly").value = Math.round(month_pay_principal);
document.querySelector("#interestMonthly").value = Math.round(month_pay_interest);
document.querySelector("#interestEmployee").value = Math.round(month_pay_interest_emp);
document.querySelector("#govtSubsidy").value = Math.round(month_subsidy_interest_govt);
document.querySelector("#employeeMonth").value = Math.round(instalment_for_employee);
document.querySelector("#emi").value = Math.round(emi);
addTable(months,amount,month_pay_interest);
}
//Calculate dynamic table with interest
function addTable(install,amount,rate) {
var table = document.querySelector("DynamicTable");
var tableBody = document.getElementById('DynamicTable').getElementsByTagName('tbody')[0];
tableBody.innerHTML = "";
for (var i = 1; i < install + 1; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 1; j < 8 + 1; j++) {
var td = document.createElement('TD');
if(i <=12){
td.appendChild(document.createTextNode(Math.round(amount)));
tr.appendChild(td);
}
if(i > 12){
td.appendChild(document.createTextNode(Math.round(rate)));
tr.appendChild(td);
}
}
}
}
.form-control:focus {
color: #212529;
background-color: #c5ffd6;
border-color: #86b7fe;
outline: 0;
box-shadow: none;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="container">
<div class="row p-3 my-4 bg-light">
<div class="col-md-6">
<form action="" method="post">
<div class="row align-items-center g-3">
<div class="col-auto">
<table class="table">
<tbody>
<tr>
<td>Loan Amount</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="loanAmount" value="100000" required></td>
</tr>
<tr>
<td>Interest Rate(%)</td>
<td><input onchange="Calculate()" type="text" class="form-control form-control-sm" id="interestRate" required></td>
</tr>
<tr>
<td>Loan Period( in Years )</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="loanPeriod" value="2" required></td>
</tr>
<tr>
<td>Grace Period </td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="gracePeriod" value="12" required></td>
</tr>
<tr>
<td>Payment Per Year </td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="paymentPerYear" value="12" required></td>
</tr>
<tr>
<td>No. of Installment </td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="instalment" readonly></td>
</tr>
<tr>
<td>No. of Installments(With Grace Period)</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="graceInstalment" readonly></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-md-6">
<div class="row align-items-center g-3">
<div class="col-auto">
<table id="inputTable" class="table">
<tbody>
<tr>
<td>Payable Total Interest</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="payableTotal" readonly></td>
</tr>
<tr>
<td>Monthly Payable Principal</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="principalMonthly" readonly></td>
</tr>
<tr>
<td>Monthly Payable Interest</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="interestMonthly" readonly></td>
</tr>
<tr>
<td>Monthly Payable Interest by Employee</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="interestEmployee" readonly></td>
</tr>
<tr>
<td>Monthly Interest Subsidy by Govt.</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="govtSubsidy" readonly></td>
</tr>
<tr>
<td>Employee to pay Monthly payment</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="employeeMonth" readonly></td>
</tr>
<tr>
<td class="text-danger">EMI</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm text-danger" id="emi" readonly></td>
</tr>
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
</div>
<hr>
<div class="container">
<div class="row p-3 bg-light">
<div class="col-md-12">
<table id="DynamicTable" class="table">
<thead>
<tr>
<th>No of Months</th>
<th>Outstandng Principals</th>
<th>Monthly Payable Principal</th>
<th>Interest Accrued</th>
<th>Monthly Payable Interest</th>
<th>Inyerest Payable by employee</th>
<th>Interest subsidy by Govt.</th>
<th>EMI</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>

Related

how to make my button appear if a condition is meet

What I'm trying to do: Create a function that automatically checks if the Grand Total value is more than 250 and if true more than 250, it will display a button and if the total is not 250 than it wonder appear
so I'm kind of confused on what I'm doing wrong here
function calculateTotal() {
// first row //
var Unit_Price_1 = document.getElementById('Unit Price_1').value;
var Quantity_1 = document.getElementById('Quantity_1').value;
var Total_1 = document.getElementById('Total_1')
var Total_Amount_1 = Unit_Price_1 * Quantity_1;
Total_1.value = Total_Amount_1
// Second row //
var Unit_Price_2 = document.getElementById('Unit Price_2').value;
var Quantity_2 = document.getElementById('Quantity_2').value;
var Total_2 = document.getElementById('Total_2')
var Total_Amount_2 = Unit_Price_2 * Quantity_2;
Total_2.value = Total_Amount_2
// grand total //
var arr = document.getElementsByName('total');
var total = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
total += parseInt(arr[i].value);
if (total < 0) {
alert("an error has occured");
total = 0
}
}
document.getElementById('total_final').value = total.toFixed(2);
function DiscountButton() {
var Amount = document.getElementsByName('total_final');
if (Amount >= 250) {
document.getElementById("dis_Button").style.visibility = "visible";
} else {
document.getElementById("dis_Button").style.visibility = "hidden";
}
}
}
<table>
<thead>
<tr>
<th>Unit Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<!---------------- ROW 1 ------------------>
<td>
<input type="number" name="unit price" placeholder="0.00" id="Unit Price_1">
</td>
<td>
<input type="number" name="Quality" placeholder="0" id="Quantity_1">
</td>
<td>
<input required type="number" name="total" value="0.00" readonly="readonly" id="Total_1" />
</td>
</tr>
<!---------------- ROW 2 ------------------>
<td>
<input type="number" name="unit price" placeholder="0.00" id="Unit Price_2">
</td>
<td>
<input type="number" name="Quality" placeholder="0" id="Quantity_2">
</td>
<td>
<input required type="number" name="total" value="0.00" readonly="readonly" id="Total_2" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input required type="button" value="Calculate Grand Total Price" onclick="calculateTotal();" />
</td>
<td colspan="2">
<input type="number" name="total_final" id="total_final" value="0.00" style="font-size: 18px; background-color: silver" readonly="readonly" />
</td>
</tr>
</tfoot>
</table>
<button id="dis_Button">Press to apply discount</button>
Amount is an element, to get it's value, use Amount.value.
<script>
function calculateTotal() {
// first row //
var Unit_Price_1 = document.getElementById('Unit Price_1').value;
var Quantity_1 = document.getElementById('Quantity_1').value;
var Total_1 = document.getElementById('Total_1')
var Total_Amount_1 = Unit_Price_1 * Quantity_1;
Total_1.value = Total_Amount_1
// Second row //
var Unit_Price_2 = document.getElementById('Unit Price_2').value;
var Quantity_2 = document.getElementById('Quantity_2').value;
var Total_2 = document.getElementById('Total_2')
var Total_Amount_2 = Unit_Price_2 * Quantity_2;
Total_2.value = Total_Amount_2
// grand total //
var arr = document.getElementsByName('total');
var total = 0;
for (var i = 0; i < arr.length; i++) {
if(parseInt(arr[i].value))
total += parseInt(arr[i].value);
if(total<0){
alert("an error has occured");
total = 0
}
}
document.getElementById('total_final').value = total.toFixed(2);
function DiscountButton(){
var Amount = +document.getElementsByName('total_final').value;
if (Amount >= 250){
document.getElementById("dis_Button").style.visibility = "visible";
}
else {
document.getElementById("dis_Button").style.visibility = "hidden";
}
} }
</script>
I found some issues.
The first issue is not call to DiscountButton() function.
The second issue is use wrong method and don't use the property value, the right way is like that.
var Amount = parseInt(document.getElementById('total_final').value);
function calculateTotal() {
// first row //
var Unit_Price_1 = document.getElementById('Unit Price_1').value;
var Quantity_1 = document.getElementById('Quantity_1').value;
var Total_1 = document.getElementById('Total_1')
var Total_Amount_1 = Unit_Price_1 * Quantity_1;
Total_1.value = Total_Amount_1
// Second row //
var Unit_Price_2 = document.getElementById('Unit Price_2').value;
var Quantity_2 = document.getElementById('Quantity_2').value;
var Total_2 = document.getElementById('Total_2')
var Total_Amount_2 = Unit_Price_2 * Quantity_2;
Total_2.value = Total_Amount_2
// grand total //
var arr = document.getElementsByName('total');
var total = 0;
for (var i = 0; i < arr.length; i++) {
if(parseInt(arr[i].value))
total += parseInt(arr[i].value);
if(total<0){
alert("an error has occured");
total = 0
}
}
//console.log(total);
document.getElementById('total_final').value = total.toFixed(2);
DiscountButton();
}
function DiscountButton(){
var Amount = parseInt(document.getElementById('total_final').value);
//console.log(Amount);
if (Amount >= 250){
document.getElementById("dis_Button").style.visibility = "visible";
}
else {
document.getElementById("dis_Button").style.visibility = "hidden";
}
}
<body>
<table>
<thead>
<tr>
<th>Unit Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<!---------------- ROW 1 ------------------>
<td>
<input type="number" name="unit price" placeholder="0.00" id="Unit Price_1" >
</td>
<td>
<input type="number" name="Quality" placeholder="0" id="Quantity_1" >
</td>
<td>
<input
required
type="number"
name="total"
value="0.00"
readonly="readonly"
id="Total_1"
/>
</td>
</tr>
<!---------------- ROW 2 ------------------>
<td>
<input type="number" name="unit price" placeholder="0.00" id="Unit Price_2">
</td>
<td>
<input type="number" name="Quality" placeholder="0" id="Quantity_2">
</td>
<td>
<input
required
type="number"
name="total"
value="0.00"
readonly="readonly"
id="Total_2"
/>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input
required
type="button"
value="Calculate Grand Total Price"
onclick="calculateTotal();"
/>
</td>
<td colspan="2">
<input
type="number"
name="total_final"
id="total_final"
value="0.00"
style="font-size: 18px; background-color: silver"
readonly="readonly"
/>
</td>
</tr>
</tfoot>
</table>
<button id="dis_Button">Press to apply discount</button>
</body>
There is not really the need for the second function DiscountButton(). That is why I simply remoced it and added an approriate line to the calculateTotal() function instead:
function calculateTotal() {
// first row //
var Unit_Price_1 = document.getElementById('Unit Price_1').value;
var Quantity_1 = document.getElementById('Quantity_1').value;
var Total_1 = document.getElementById('Total_1')
var Total_Amount_1 = Unit_Price_1 * Quantity_1;
Total_1.value = Total_Amount_1
// Second row //
var Unit_Price_2 = document.getElementById('Unit Price_2').value;
var Quantity_2 = document.getElementById('Quantity_2').value;
var Total_2 = document.getElementById('Total_2')
var Total_Amount_2 = Unit_Price_2 * Quantity_2;
Total_2.value = Total_Amount_2
// grand total //
var arr = document.getElementsByName('total');
var total = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
total += parseInt(arr[i].value);
if (total < 0) {
alert("an error has occured");
total = 0
}
}
document.getElementById('total_final').value = total.toFixed(2);
document.getElementById("dis_Button").style.visibility = total>250 ? "visible":"hidden";
}
<table>
<thead>
<tr>
<th>Unit Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<!---------------- ROW 1 ------------------>
<td>
<input type="number" name="unit price" placeholder="0.00" id="Unit Price_1">
</td>
<td>
<input type="number" name="Quality" placeholder="0" id="Quantity_1">
</td>
<td>
<input required type="number" name="total" value="0.00" readonly="readonly" id="Total_1" />
</td>
</tr>
<!---------------- ROW 2 ------------------>
<td>
<input type="number" name="unit price" placeholder="0.00" id="Unit Price_2">
</td>
<td>
<input type="number" name="Quality" placeholder="0" id="Quantity_2">
</td>
<td>
<input required type="number" name="total" value="0.00" readonly="readonly" id="Total_2" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input required type="button" value="Calculate Grand Total Price" onclick="calculateTotal();" />
</td>
<td colspan="2">
<input type="number" name="total_final" id="total_final" value="0.00" style="font-size: 18px; background-color: silver" readonly="readonly" />
</td>
</tr>
</tfoot>
</table>
<button id="dis_Button">Press to apply discount</button>

How to add days based on input value in each rows of the dynamic table using javascript

My problem is, I have to add days based on the input given in the text box for all the rows of the dynamic table.
I have added days for 2 row but 3,4... row displaying the value of 2 row.
Now I want to add days in the 3rd row and goes on..........
<script type="text/javascript">
$(function(){
$("body").on("focusout",function(){
var trLength=$('body #appendRows tr').length;
for (var i = 1; i <trLength; i++) {
$('#appendRows tr:nth-child(2)').remove();
}
var val = $(".ND").val();
var m = $("#follow_Date").val();
var j = $("#Amount").val();
var k = document.getElementById('txtDate').value;
var date = new Date(k);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() +
parseInt(m));
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var y = newdate.getFullYear();
var someFormattedDate = mm+ '/' + dd + '/' + y;
var i=1;
for(i==1;i<val;i++){
var html = $("#appendRows tr:first-child").clone();
html.find("input").val("");
html.find('input[name^="Sno"]').val(i+1);
html.find('input[name^="Date"]').val(someFormattedDate + parseInt(m));
html.find('input[name^="Amount"]').val(j);
console.log(date, i, someFormattedDate)
$('#appendRows').append(html);
}
});
})
</script>
This is a javascript code for creating table..............
This is my dynamic table,it will created based on input value in the text field...
<table class='table table-hover table-bordered table-striped table-xxs' id="cartGrid">
<thead>
<tr>
<th>Sno</th>
<th >Date</th>
<th >Amount</th>
<th >Bank Name</th>
<th >Chqamt</th>
<th >Payable</th>
<th>Bank1</th>
<th >Chqamt1</th>
<th >Payable1</th>
</tr>
</thead>
<tbody id="appendRows">
<tr>
<td ><input style="width:40px" type="text" class="form-control" name="Sno[]" value="1" id="Sno"></td>
<td><input style="width:80px" type="text" class="form-control" name="Date[]" value="" id="Date"></td>
<td> <input style="width:70px" type="text" class="form-control" name="Amount[]" value="" id="Amount"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Bankname[]" id="Bankname"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Chqamt[]" id="Chqamt"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Payable[]" id="Payable"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Bank1[]" id="Bank1"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Chqamt1[]" id="Chqamt1"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Payable1[]" id="Payable1"></td>
</tr>
</tbody>
</table>
This is table code..................
<label class="col-lg-1 control-label" id="pd">Due Start:</label>
<div class="col-lg-3">
<div class="row">
<div class="col-lg-4">
<input type="text" class="form-control input-xs datepicker-dates Dues" placeholder="Due Start Date…" id="txtDate" name="TDDate" value="">
</div>
</div>
</div>
</div>
</div>
</fieldset>
<div class="col-md-2">
<div class="form-group">
<fieldset>
<label class="col-lg-1 control-label" id="pd">Mode:</label>
<div class="col-lg-3">
<div class="row">
<div class="col-lg-4">
<input type="number" id="follow_Date" placeholder="Mode" name="TMode" class="form-control input-xs Mode">
</div>
</div>
</div>
</div>
This is due start and mode text box code.........
Updated
$(function(){
$('#txtDate, #follow_Date, .ND').keyup( function () {
// Clear rows
var trLength = $('body #appendRows tr').length;
for (var i = 1; i <trLength; i++) {
$('#appendRows tr:nth-child(2)').remove();
}
var val = (!$(".ND").val()) ? 1 : val = $(".ND").val();
var m = $("#follow_Date").val();
var j = $("#Amount").val();
var k = document.getElementById('txtDate').value;
var currentDate = moment(k);
for (var i = 0, len = val; i < val; ++i) {
var newdate = currentDate.add(parseInt(m), 'days');
var html = $("#appendRows tr:first-child").clone();
html.find("input").val("");
html.find('input[name^="Sno"]').val(i+1);
html.find('input[name^="Amount"]').val(j);
// I format this to make it clear
html.find('input[name^="Date"]')
.val(newdate.format('YYYY/MM/DD'));
$('#appendRows').append(html);
}
// Remove that first row
$("#appendRows tr:first-child").remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
<div>
<label class="col-lg-1 control-label" id="pd">Due Start:</label>
<div class="col-lg-3">
<div class="row">
<div class="col-lg-4">
<input type="text" class="form-control input-xs datepicker-dates Dues" placeholder="Due Start Date…" id="txtDate" name="TDDate" value="2018/12/12">
</div>
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<fieldset>
<label class="col-lg-1 control-label" id="pd">Mode:</label>
<div class="col-lg-3">
<div class="row">
<div class="col-lg-4">
<input type="number" id="follow_Date" placeholder="Mode" name="TMode" class="form-control input-xs Mode" value="30">
</div>
</div>
</div>
<label class="col-lg-1 control-label" id="pd">Rows:</label>
<div class="col-lg-3">
<div class="row">
<div class="col-lg-4">
<input type="number" class="ND" placeholder="Number of rows" name="TMode" class="form-control input-xs Mode" value="10">
</div>
</div>
</div>
</fieldset>
</div>
</div>
<table class='table table-hover table-bordered table-striped table-xxs' id="cartGrid">
<thead>
<tr>
<th>Sno</th>
<th >Date</th>
<th >Amount</th>
<th >Bank Name</th>
<th >Chqamt</th>
<th >Payable</th>
<th>Bank1</th>
<th >Chqamt1</th>
<th >Payable1</th>
</tr>
</thead>
<tbody id="appendRows">
<tr>
<td ><input style="width:40px" type="text" class="form-control" name="Sno[]" value="1" id="Sno"></td>
<td><input style="width:80px" type="text" class="form-control" name="Date[]" value="" id="Date"></td>
<td> <input style="width:70px" type="text" class="form-control" name="Amount[]" value="" id="Amount"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Bankname[]" id="Bankname"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Chqamt[]" id="Chqamt"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Payable[]" id="Payable"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Bank1[]" id="Bank1"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Chqamt1[]" id="Chqamt1"></td>
<td ><input style="width:80px" type="text" class="form-control" name="Payable1[]" id="Payable1"></td>
</tr>
</tbody>
</table>
Based on comments, use keyup event on the Mode input to add rows when you enter number into the Mode input...and just add 0 days to the first occurence of the date
function add() {
var val = $(".Mode").val();
var currentdate = document.getElementById('txtDate').value;
currentdate = getDueDate(currentdate, 0);
$("#appendRows tr").not('.master-row').remove(); // remove previous rows (reset the table)
for (var i = 0; i < val; i++) {
var someFormattedDate = formatDate(currentdate);
var html = $("#appendRows tr:first-child").clone();
html.find("input").val("");
html.find('input[name^="Sno"]').val(i + 1);
html.find('input[name^="Date"]').val(someFormattedDate);
html.removeClass('master-row');
$('#appendRows').append(html);
currentdate = getDueDate(currentdate, val);
}
}
function formatDate(date) {
var dd = date.getDate();
var mm = date.getMonth() + 1;
var y = date.getFullYear();
return mm + '/' + dd + '/' + y;
}
function getDueDate(from, days) {
var fromDate = new Date(from);
var dueDate = new Date(from);
dueDate.setDate(fromDate.getDate() + days * 1);
return dueDate;
}
add();
$('.Mode').on('keyup', function() {
add();
});
.master-row {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
the data
<div>
<input type="text" class="Mode" value="3">
<input type="text" id="txtDate" value="12/29/2018">
</div>
<div style="height:20px">
</div>
the table
<table id="appendRows">
<tr class="master-row">
<td><input type="text" name="Sno"></td>
<td><input type="text" name="Date"></td>
</tr>
</table>
To hide "master-row" i would do something like this, also its better to break code to the separate functions

Suming up dynamic table last column javascript

Please someone should help out on this, everything seems to be working fine but the sumQTY() function is where am having problem with, its iterating through the row cells but just not identifing the input box. Thanks
Bellow is the script.'
How do i get the sumQTY() to work well.
<SCRIPT language="javascript">
function addRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
if (rowCount < 4) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
row.id = 'row_'+rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[1].cells[i].outerHTML;
}
var listitems= row.getElementsByTagName("input")
for (i=0; i<listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
}
} else {
alert("Maximum Row Reached.");
}
}
function deleteRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null !== chkbox && true === chkbox.checked) {
if (rowCount <= 2) { // limit the user from removing all the fields
alert("Cannot Remove all the Rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll('[id=item')[0].value;
var myBox2 = mainRow.querySelectorAll('[id=price')[0].value;
var total = mainRow.querySelectorAll('[id=qty')[0];
var myResult1 = myBox1 * (parseFloat(myBox2)) ;
var mresult = myResult1.toFixed(2);
total.value = mresult;
}
function sumQty(dataTable) {
var total = 0;
var confirm = 10;
var colCount;
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
colCount = row.cells.length;
for (var j = 0; j < colCount; j++) {
var node = row.cells[j].childNodes[0];
if (node.name == "qty[]") {
total += parseInt(node.value);
confirm = confirm + 1;
}else{confirm = confirm - 1;}
}
}
//alert("total = " + total + " " + rowCount + " " + colCount + " " + confirm);
//document.getElementById("mee").innerHTML = "Sum Value = " + total;
//console.log(sumVal);
return total;
}
</SCRIPT>
Bellow is the html table code
<form action="" method="post" name="f">
<table id="dataTable" class="form">
<thead>
<th style="width:20px"></th>
<th>Item</th>
<th>Description</th>
<th>Unit Price</th>
<th>Item Units</th>
<th>Total Price (#)</th>
</thead>
<tbody>
<tr id='row_0'>
<td><input style="width:20px" type="checkbox" name="chkbox[]" /></td>
<td>
<input type="text" required="required" name="ite[]" onChange="search('row_1')" id="ite" placeholder="Item">
</td>
<td>
<input type="text" required="required" class="small" name="price[]" id="des" placeholder="Description">
</td>
<td>
<input type="text" required="required" name="item[]" oninput="calculate('row_0')" onchange="sumQty()" id="item" placeholder="unit price">
</td>
<td>
<input type="text" required="required" class="small" name="price[]" oninput="calculate('row_0')" id="price" placeholder="units">
</td>
<td>
<input type="text" required="required" class="small" name="qty[]" id="qty" placeholder="total price">
</td>
</tr>
</tbody>
</table>
<span id="mee"></span>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<input type="button" value="Remove" onClick="deleteRow('dataTable')" />
<INPUT type="submit" value="Insert" name="submit" />
<input type="text" required="required" class="small" name="sumtotal" placeholder="total price"/>
</form>
I want to output the total sum of the last col in the input field with name="sumtotal".
Thanks.
You will have to work a bit more on when the sumQTy is being called, since when it gets called the row price = NaN since there is no given a quantity, you can overwrite that behavior by making a small change in the calculate function or having a starter value o "1" in the qty.
This are the changes I made it to have it working:
In your HTML
<input type="text" required="required" class="small" name="price[]" oninput="calculate('row_0')" id="price" placeholder="units" value="1">
In calculate function
var multiplier = Number(myBox2) || 1;
var myResult1 = myBox1 * multiplier;
Better implementation of sumQty
function sumQty(dataTable) {
var confirm = 10;
var colCount;
var table = document.getElementById("dataTable");
let rows = [...table.querySelectorAll('[name*=qty]')];
let total = rows.reduce((prev, current)=>{
let to_be_added = Number(current.value) || 0;
return prev + to_be_added;
},0)
return total;
}
<SCRIPT language="javascript">
function addRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
if (rowCount < 4) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
row.id = 'row_'+rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[1].cells[i].outerHTML;
}
var listitems= row.getElementsByTagName("input")
for (i=0; i<listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
}
} else {
alert("Maximum Row Reached.");
}
}
function deleteRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null !== chkbox && true === chkbox.checked) {
if (rowCount <= 2) { // limit the user from removing all the fields
alert("Cannot Remove all the Rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll('[id=item')[0].value;
var myBox2 = mainRow.querySelectorAll('[id=price')[0].value;
var total = mainRow.querySelectorAll('[id=qty')[0];
var multiplier = Number(myBox2) || 1;
var myResult1 = myBox1 * multiplier;
//var myResult1 = myBox1 * (parseFloat(myBox2)) ;
var mresult = myResult1.toFixed(2);
total.value = mresult;
//function sumQty(dataTable) {
var confirm = 10;
var colCount;
var table = document.getElementById("dataTable");
let rows = [...table.querySelectorAll('[name*=qty]')];
let total2 = rows.reduce((prev, current)=>{
let to_be_added = Number(current.value) || 0;
return prev + to_be_added;
},0)
console.log(total2);
$("#sumtotal").val(total2.toFixed(2));
return total2;
}
function amountDue() {
var amount = parseFloat($("#sumtotal").val());
var paidd = parseFloat($("#paid").val());
var balance = amount - paidd;
$("#due").val(balance.toFixed(2));
$("#due2").val(balance.toFixed(2));
}
html code!
<form action="" method="post">
<article>
<div>
<address>
<p>Customer ID=<br>Staff ID= <?php echo $_SESSION['staffid']?></p>
</address>
<table class="meta">
<tr>
<th><span>invoice #</span></th>
<td><input type="text" name="ind"/></td>
</tr>
<tr>
<th><span>Amount Due</span></th>
<td><input type="text" required="required" class="small" name="" id="due2" placeholder="#" readonly="readonly" style="background-color: white" /></td>
</tr>
</table>
</div>
</article>
<article>
<table id="dataTable" class="form">
<thead>
<th style="width:20px"></th>
<th>Item</th>
<th>Description</th>
<th>Unit Price</th>
<th>Item Units</th>
<th>Sub Total (#)</th>
</thead>
<tbody>
<tr id='row_0'>
<td><input style="width:20px" type="checkbox" name="chkbox[]" /></td>
<td>
<select required="required" name="" onChange="" id="" placeholder="Item">
<option value="0"> select an item</option>
<option value="1"></option>
<option value="2"></option>
</select>
</td>
<td>
<input type="text" required="required" class="small" name="" id="" placeholder="Description">
</td>
<td>
<input type="text" required="required" name="item[]" oninput="calculate('row_0')" id="item" placeholder="unit price">
</td>
<td>
<input type="text" required="required" class="small" name="price[]" oninput="calculate('row_0')" id="price" placeholder="units" value="1">
</td>
<td>
<input type="text" required="required" class="small" name="qty[]" id="qty" placeholder="sub total" readonly="readonly" style="background-color: white">
</td>
</tr>
</tbody>
</table>
<span id="mee"></span>
<input type="button" value="Add" onClick="addRow('dataTable')" class="butto" />
<input type="button" value="Remove" onClick="deleteRow('dataTable')" class="butto"/>
<table class="balance" id="datatable2">
<tr>
<th><span>Total</span></th>
<td><input type="text" required="required" class="small" name="tot" id="sumtotal" placeholder="total price" readonly="readonly" style="background-color: white"/></td>
</tr>
<tr>
<th><span>Amount Paid</span></th>
<td><input type="text" required="required" class="small" name="" id="paid" placeholder="#" oninput="amountDue()"></td>
</tr>
<tr>
<th><span>Balance Due</span></th>
<td><input type="text" required="required" class="small" name="" id="due" placeholder="#" readonly="readonly" style="background-color: white"></td>
</tr>
</table>
</article>
<aside><center>
<h1><span>Additional Notes</span></h1>
</center>
<div contenteditable>
<p>Enter additional info here</p>
</div>
</aside>
</ul>
<ul id="core" class="hide" style="overflow-x:auto; overflow-y:auto;">
</ul>
<ul id="jquerytuts" class="hide" style="overflow-x:auto; overflow-y:auto;">
</ul>
<ul id="classics" class="hide">
</ul>
</div> <!-- END List Wrap -->
<center>
<div class="input-container">
<INPUT type="submit" value="Insert" name="submit" class="butto" style="width:100%"/>
</div>
</form>

Sum Javascript multiple fields

I have problem again with javascript, i want to ask how to sum from fields?
where is the problem?
I am trying to sum all my fields using getElementsByName and getElementsById. I want to show total sum of values entered in sub total input boxes in next input box named total without refreshing page.
Can anyone will help me to figure it out..?
Here my code
$(document).on('keyup', '.input', function() {
var num1 = $(this).parents('tr:first').find('.input:first').val();
var num2 = $(this).parents('tr:first').find('.input:last').val();
$(this).parents('tr:first').find('.sub-total').val(to_rupiah(num1 * num2));
var arr = document.getElementsByName('.sub-total');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalBayar').value = tot;
});
$(document).ready(function() {
var index = 2;
$("#addCF").click(function() {
$("#customFields").append('<tr><td>' + index + '</td><td><input class="form-control" name="kode_barang[]" placeholder="Ketik Kode / Nama Barang" type="text"></td><td><input class="form-control input input1" name="harga_satuan[]" id="input1" value="" type="text"></td><td><input class="form-control input input2" id="input2" name="jumlah_beli[]" type="text"></td><td><input class="form-control sub-total" name="sub_total[]" onblur="findTotal()" value="" id="output" type="text"></td><td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td></tr>');
index++;
});
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
});
function to_rupiah(angka) {
var rev = parseInt(angka, 10).toString().split('').reverse().join('');
var rev2 = '';
for (var i = 0; i < rev.length; i++) {
rev2 += rev[i];
if ((i + 1) % 3 === 0 && i !== (rev.length - 1)) {
rev2 += '.';
}
}
return 'Rp. ' + rev2.split('').reverse().join('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<table class='table table-bordered' id='customFields'>
<thead>
<tr>
<th style='width:35px;'>#</th>
<th style='width:210px;'>Nama Barang</th>
<th style='width:120px;'>Harga</th>
<th style='width:75px;'>Qty</th>
<th style='width:125px;'>Sub Total</th>
<th style='width:40px;'></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input class="form-control" name="kode_barang[]" id="cariBrg" placeholder="Ketik Kode / Nama Barang" type="text">
</td>
<td><input class="form-control input" name="harga_satuan[]" id="input1" value="" type="text"></td>
<td><input class="form-control input" id="input2" name="jumlah_beli[]" type="text"></td>
<td><input class="form-control sub-total" name="sub_total[]" id="output" onblur="findTotal()" type="text"></td>
<td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td>
</tr>
</tbody>
</table>
<div class='alert alert-info TotalBayar'>
<button id='addCF' class='btn btn-default pull-left'><i class='fa fa-plus fa-fw'></i> Baris Baru (F7)</button>
<h2>Total : <span id='TotalBayar'>0</span></h2>
Please Help
getElementsByName(".sub-total") looks for elements with name=".sub-total", but you don't have that, it's a class. You can use $(".sub-total") to get these elements and loop over them.
document.getElementById('TotalBayar').value = tot;
won't work because TotalBayar is a DIV, and .value is only valid for inputs. Use $("#TotalBayar").text(tot) to set its contents.
You also can't just call parseInt() on the value in the sub-total fields, because they begin with Rp.. I've used a regular expression to get the number out of the value.
BTW, instead of .parents("tr:first") you can use .closest("tr").
$(document).on('keyup', '.input', function() {
var num1 = $(this).closest('tr').find('.input:first').val();
var num2 = $(this).closest('tr').find('.input:last').val();
$(this).closest('tr').find('.sub-total').val(to_rupiah(num1 * num2));
var arr = document.getElementsByName('.sub-total');
var tot = 0;
$(".sub-total").each(function() {
var val = parseInt($(this).val().match(/\d+/)[0]);
if (val) {
tot += val;
}
});
$('#TotalBayar').text(tot);
});
$(document).ready(function() {
var index = 2;
$("#addCF").click(function() {
$("#customFields").append('<tr><td>' + index + '</td><td><input class="form-control" name="kode_barang[]" placeholder="Ketik Kode / Nama Barang" type="text"></td><td><input class="form-control input input1" name="harga_satuan[]" id="input1" value="" type="text"></td><td><input class="form-control input input2" id="input2" name="jumlah_beli[]" type="text"></td><td><input class="form-control sub-total" name="sub_total[]" onblur="findTotal()" value="" id="output" type="text"></td><td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td></tr>');
index++;
});
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
});
function to_rupiah(angka) {
var rev = parseInt(angka, 10).toString().split('').reverse().join('');
var rev2 = '';
for (var i = 0; i < rev.length; i++) {
rev2 += rev[i];
if ((i + 1) % 3 === 0 && i !== (rev.length - 1)) {
rev2 += '.';
}
}
return 'Rp. ' + rev2.split('').reverse().join('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<table class='table table-bordered' id='customFields'>
<thead>
<tr>
<th style='width:35px;'>#</th>
<th style='width:210px;'>Nama Barang</th>
<th style='width:120px;'>Harga</th>
<th style='width:75px;'>Qty</th>
<th style='width:125px;'>Sub Total</th>
<th style='width:40px;'></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input class="form-control" name="kode_barang[]" id="cariBrg" placeholder="Ketik Kode / Nama Barang" type="text">
</td>
<td><input class="form-control input" name="harga_satuan[]" id="input1" value="" type="text"></td>
<td><input class="form-control input" id="input2" name="jumlah_beli[]" type="text"></td>
<td><input class="form-control sub-total" name="sub_total[]" id="output" onblur="findTotal()" type="text"></td>
<td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td>
</tr>
</tbody>
</table>
<div class='alert alert-info TotalBayar'>
<button id='addCF' class='btn btn-default pull-left'><i class='fa fa-plus fa-fw'></i> Baris Baru (F7)</button>
<h2>Total : <span id='TotalBayar'>0</span></h2>

how can i get the total of all dynamically calculated subtotals

I want all my grand totals to be summed up at the end i.e..total amount to be displayed
I've coded using handlebars.js as
<input type="button" value="Add Product" onClick="addRow('dataTable')" />
<table id="dataTable" class="form" border="0">
<tbody>
<tr id='row_0'>
<p>
<td>
<label>productcode</label>
<input type="text" required="required" name="pcode" size="10px" >
</td>
<td>
<label>productname</label>
<input type="text" required="required" name="name" size="10px">
</td>
<td>
<label>Quantity</label>
<input type="text" required="required" name="qty" oninput="calculate('row_0')" size="10px">
</td>
<td>
<label for="price">Price</label>
<input type="text" required="required" class="small" name="price" oninput="calculate('row_0')" size="10px">
</td>
<td>
<label for="total">Total</label>
<input type="text" required="required" class="small" name="total" size="10px">
</td>
<td>
<label>tax</label>
<input type="text" required="required" name="tax" oninput="calculate('row_0')" size="10px">
</td>
<td>
<label>discount</label>
<input type="text" required="required" name="discount" oninput="calculate('row_0')" size="10px">
</td>
<td>
<label>grand total</label>
<input type="text" required="required" name="gtotal" class="small" size="10px" >
</td>
<tr>
<table class="table invoice-table text-right">
<td style="border-top: none;"> Total Amount</td>
<td style="border-top: none;"><strong class="total- price">£0</strong></td>
</tr>
</table>
</p>
</tr>
</tbody>
</table>
</html>
JS code:
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 200) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = 'row_'+rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems= row.getElementsByTagName("input")
for (i=0; i<listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
}
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null !== chkbox && true === chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var quantity = mainRow.querySelectorAll('[name=qty]')[0].value;
var price = mainRow.querySelectorAll('[name=price]')[0].value;
var total = mainRow.querySelectorAll('[name=total]')[0];
var myResult1 = quantity * price;
total.value = myResult1;
var tax = mainRow.querySelectorAll('[name=tax]')[0].value;
var discount = mainRow.querySelectorAll('[name=discount]')[0].value;
var gtotal = mainRow.querySelectorAll('[name=gtotal]')[0];
var myResult2 = ((price*quantity*tax*0.01)-(price*quantity*discount*0.01))+(price*quantity);
gtotal.value = myResult2;
}
</script>
now the grand total should be automatically summed and displayed at total amount

Categories