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>
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>
I'm working with a checkbox which will disable amount textfield in the incoming added rows if the checkbox is unchecked and will enable the lot_price textfield if check.
IF(checkbox is checked) = Enable lot_price field and disable the incoming amount rows
IF(checkbox is unchecked) = Disable lot_price field and enable the incoming amount rows
Here is the current code
function disable() {
var elements = document.getElementsByClassName("amount");
document.getElementById("state").checked ? doIt(elements, true) : doIt(elements, false);
}
function doIt(elements, status) {
for (var i = 0; i < elements.length; i++) {
elements[i].disabled = status;
}
}
var rowCount = $('#table_body tr').length;
var m;
var month_label;
var check = document.getElementById("state");
if (check.checked) {
} else {
}
$(document).ready(function() {
$("#add_row").click(function(e) {
$('tr').find('input').prop('enabled', true)
$('#addr' + rowCount).html('<td><input type="text" id="item_no" name="item_no[' + rowCount + ']" placeholder="" class="form-control" autocomplete="off"></td>' +
'<td><input type="text" id="stock_no" name="stock_no[' + rowCount + ']" placeholder="Stock No" class="form-control" autocomplete="off"></td>' +
'<td><input type="text" id="unit" name="unit[' + rowCount + ']" placeholder="Unit" class="form-control" autocomplete="off"></td>' +
'<td><textarea name="description[' + rowCount + ']" id="description" rows="1" placeholder="Description" class="form-control" required></textarea></td>' +
'<td><input type="text" id="quantity' + rowCount + '" name="quantity[' + rowCount + ']" placeholder="Quantity" class="form-control" onkeypress="return isNumberKeyQTY(event)" autocomplete="off">' +
'<td><input type="text" id="unit_cost' + rowCount + '" name="unit_cost[' + rowCount + ']" placeholder="Unit Cost" class="form-control" onkeypress="return isNumberKeyUCOST(event)" autocomplete="off"></td>' +
'<td><input type="text" id="amount' + rowCount + '" name="amount[' + rowCount + ']" placeholder="Amount" class="form-control amount" required></td>'
);
$('#tab_logic').append('<tr id="addr' + (rowCount + 1) + '"></tr>');
rowCount++;
});
});
//This will Remove the row
//before the last row then
//changes the id of the last
//row which is hidden
$('#remove_row').click(function() {
var row_count_minus_btn = $('#table_body tr').length - 1
if ($('#table_body tr').length != 2) {
$("#table_body tr:nth-last-child(2)").remove();
$('#table_body tr:last-child').attr('id', 'addr' + row_count_minus_btn);
rowCount--;
} else {
swal("Oops...", "Cannot Delete First Row!", "warning");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="state" id="state" onclick="disable()">Check
<input type="text" id="lot_price" name="lot_price" placeholder="" class="form-control" value="" />
<table id="tab_logic">
<thead>
<tr>
<th style="width: 4%; text-align: center;">Item<br> No.</th>
<th style="width:10%; text-align: center">Stock No.</th>
<th style="width:10%; text-align: center">Unit</th>
<th style="width:36%; text-align: center">Description</th>
<th style="width:10%; text-align: center">Quantity</th>
<th style="width:15%; text-align: center">Unit Cost</th>
<th style="width:15%; text-align: center">Amount</th>
</tr>
</thead>
<tbody id="table_body">
<tr id='addr1'>
<td><input type="text" id="item_no" name="item_no[1]" placeholder="" class="form-control" autocomplete="off"></td>
<td><input type="text" id="stock_no" name="stock_no[1]" placeholder="Stock No" class="form-control" autocomplete="off"></td>
<td><input type="text" id="unit" name="unit[1]" placeholder="Unit" class="form-control" autocomplete="off"></td>
<td><textarea name="description[1]" id="description" rows="1" placeholder="Description" class="form-control" required></textarea></td>
<td><input type="text" id="quantity0" name="quantity[1]" placeholder="Quantity" class="form-control" onkeypress='return isNumberKeyQTY(event)' autocomplete="off"></td>
<td><input type="text" id="unit_cost0" name="unit_cost[1]" placeholder="Unit Cost" class="form-control" onkeypress='return isNumberKeyUCOST(event)' autocomplete="off"></td>
<td><input type="text" id="amount0" name="amount[1]" placeholder="Amount" class="form-control amount" required></td>
</tr>
<tr id="addr2">
</tbody>
</table>
<button type="button" id="add_row" style="display: inline;" class="btn btn-primary btn-md center-block">Add More Rows <span class="glyphicon glyphicon-plus"></span></button>
<button type="button" id="remove_row" style="display: inline;" class="btn btn-danger btn-md center-block">Delete Last Row <span class="glyphicon glyphicon-remove"></span></button>
Please add some logic to your function
Disable your lot_price on initial
Missing logic to enable/disable lot_price when checkbox was check/uncheck
function disable(){
...
...
// Enable/disable lot_price
}
Missing logic to enable/disable amount textbox when add new row to list
$('#addr' + rowCount).html(
...
+ '<td><input type="text" id="amount' + rowCount + '" name="amount[' + rowCount + ']" placeholder="Amount" class="form-control amount" required '
+ ( document.getElementById("state").checked?"disabled":"")
+'></td>');
Please run below snippet for test
function disable() {
var elements = document.getElementsByClassName("amount");
document.getElementById("state").checked ? doIt(elements, true) : doIt(elements, false);
// Enable/disable lot_price
document.getElementById("lot_price").disabled = !document.getElementById("state").checked;
}
function doIt(elements, status) {
for (var i = 0; i < elements.length; i++) {
elements[i].disabled = status;
}
}
var rowCount = $('#table_body tr').length;
var m;
var month_label;
var check = document.getElementById("state");
if(check.checked){
}else{
}
$(document).ready(function() {
$("#add_row").click(function(e) {
$('tr').find('input').prop('enabled',true)
$('#addr' + rowCount).html('<td><input type="text" id="item_no" name="item_no[' + rowCount + ']" placeholder="" class="form-control" autocomplete="off"></td>'
+ '<td>...</td>'
+ '<td><input type="text" id="amount' + rowCount + '" name="amount[' + rowCount + ']" placeholder="Amount" class="form-control amount" required '+( document.getElementById("state").checked?"disabled":"")+'></td>'
);
$('#tab_logic').append('<tr id="addr' + (rowCount + 1) + '"></tr>');
rowCount++;
});
});
//This will Remove the row
//before the last row then
//changes the id of the last
//row wich is hidden
$('#remove_row').click(function(){
var row_count_minus_btn = $('#table_body tr').length - 1
if($('#table_body tr').length != 2){
$("#table_body tr:nth-last-child(2)").remove();
$('#table_body tr:last-child').attr('id', 'addr' + row_count_minus_btn);
rowCount--;
}else{
console.log("Oops...", "Cannot Delete First Row!", "warning");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="state" id="state" onclick="disable()">Check
<input type="text" id="lot_price" name="lot_price" placeholder="" class="form-control" value="" disabled/>
<table id="tab_logic">
<thead>
<tr>
<th>Item No.</th>
<th>...</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="table_body">
<tr id='addr1'>
<td><input type="text" id="item_no" name="item_no[1]" placeholder="" class="form-control" autocomplete="off"> </td><td>...
</td> <td><input type="text" id="amount0" name="amount[1]" placeholder="Amount" class="form-control amount" required></td>
</tr>
<tr id="addr2">
</tbody>
</table>
<button type="button" id="add_row" style="display: inline;" class="btn btn-primary btn-md center-block" >Add More Rows <span class="glyphicon glyphicon-plus"></span></button>
<button type="button" id="remove_row" style="display: inline;" class="btn btn-danger btn-md center-block" >Delete Last Row <span class="glyphicon glyphicon-remove"></span></button>
I need convert the total amount in to words with jquery in a script file.
I have the total value calculated and put int to id=(#grandT) and the same value should be converted in to words(Rupees/Indian numbering system) in textarea (#word)
https://en.wikipedia.org/wiki/Indian_numbering_system
Script File
$(document).ready(function() {
$(".input").keyup(function() {
var valp1 = +$(".prec1").val();
var valr1 = +$(".rate1").val();
var valq1 = +$(".qty1").val();
var valp2 = +$(".prec2").val();
var valr2 = +$(".rate2").val();
var valq2 = +$(".qty2").val();
$("#Gst1").val((valr1 * valq1) * valp1 / 100);
$("#Gst2").val((valr2 * valq2) * valp2 / 100);
});
$(".input").keyup(function() {
var val1 = +$(".rate1").val();
var val2 = +$(".qty1").val();
var val3 = +$(".rate2").val();
var val4 = +$(".qty2").val();
var valp1 = +$(".prec1").val();
var valp2 = +$(".prec2").val();
var valr1 = +$(".rate1").val();
var valr2 = +$(".rate2").val();
var valq1 = +$(".qty1").val();
var valq2 = +$(".qty2").val();
$("#result1").val(val1 * val2);
$("#result2").val(val3 * val4);
$("#grandT").val(((val1 * val2) + (val3 * val4)) + ("/-"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript" src="Script.js"></script>
<link rel="stylesheet" href="StyleSheet.css">
</head>
<body>
<page size="A4">
<div class="rowmain">
<table>
<thead class="th1">
<tr>
<th>PRECENTAGE</th>
<th>RATE</th>
<th>QTY</th>
<th>GST <br> AMOUNT
</th>
<th>AMOUNT</th>
</tr>
</thead>
<tbody>
<tr>
<td valign="middle"><input type="number" class="input prec1" value="" style="width: 3em" name="pre"></td>
<td valign="middle"><input type="number" name="rate" class="input rate1" value="" style="width: 5em"></td>
<td valign="middle"><input type="number" name="qty" class="input qty1" value="" style="width: 5em"></td>
<td valign="middle"><input disabled="disabled" id="Gst1" style="width: 6.5em" name="gst"></td>
<td valign="middle"><input disabled="disabled" class="text-right" id="result1" name="result1" class="input result1" value="" style="width: 7.4em"></td>
</tr>
<tr>
<td valign="middle"><input type="number" class="input prec2" value="" style="width: 3em" name="pre"></td>
<td valign="middle"><input type="number" name="rate" class="input rate2" value="" style="width: 5em"></td>
<td valign="middle"><input type="number" name="qty" class="input qty2" value="" style="width: 5em"></td>
<td valign="middle"><input disabled="disabled" id="Gst2" style="width: 6.5em" name="gst2"></td>
<td valign="middle"><input disabled="disabled" class="text-right" id="result2" name="result2" class="input result2" style="width: 7.4em"></td>
</tr>
</tbody>
</table>
</div>
<div class="rowmain">
<div class="leftttext">
<table class="th1">
<tr>
<th>Rupees in Words</th>
<td><textarea id="word" rows="2" cols="60"></textarea></td>
</tr>
</table>
</div>
<div class="righttext">
<table>
<tr>
<th class="thG">Grand Total</th>
<td><input disabled="disabled" class="text1" id="grandT" value="" style="width: 8em"></td>
</tr>
</table>
</div>
</div>
</page>
</body>
</html>
Here's a working snippet of what you wanted to achieve, as already suggested the conversion to word is done by the snippet in answer here: Convert digits into words with JavaScript, I recommend you read and look at the published package if that's more useful for you.
/*
* taken from
* https://stackoverflow.com/questions/14766951/convert-digits-into-words-with-javascript
*/
var a = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
var b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function inWords(num) {
if ((num = num.toString()).length > 9) return 'overflow';
n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
if (!n) return;
var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';
return str;
}
$(document).ready(function() {
$(".input").keyup(function() {
var valp1 = +$(".prec1").val();
var valr1 = +$(".rate1").val();
var valq1 = +$(".qty1").val();
var valp2 = +$(".prec2").val();
var valr2 = +$(".rate2").val();
var valq2 = +$(".qty2").val();
$("#Gst1").val((valr1 * valq1) * valp1 / 100);
$("#Gst2").val((valr2 * valq2) * valp2 / 100);
});
$(".input").keyup(function() {
var val1 = +$(".rate1").val();
var val2 = +$(".qty1").val();
var val3 = +$(".rate2").val();
var val4 = +$(".qty2").val();
var valp1 = +$(".prec1").val();
var valp2 = +$(".prec2").val();
var valr1 = +$(".rate1").val();
var valr2 = +$(".rate2").val();
var valq1 = +$(".qty1").val();
var valq2 = +$(".qty2").val();
$("#result1").val(val1 * val2);
$("#result2").val(val3 * val4);
var total = (val1 * val2) + (val3 * val4);
$("#grandT").val(total + "/-");
$("#word").val(inWords(total));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript" src="Script.js"></script>
<link rel="stylesheet" href="StyleSheet.css">
</head>
<body>
<page size="A4">
<div class="rowmain">
<table>
<thead class="th1">
<tr>
<th>PRECENTAGE</th>
<th>RATE</th>
<th>QTY</th>
<th>GST <br> AMOUNT
</th>
<th>AMOUNT</th>
</tr>
</thead>
<tbody>
<tr>
<td valign="middle"><input type="number" class="input prec1" value="" style="width: 3em" name="pre"></td>
<td valign="middle"><input type="number" name="rate" class="input rate1" value="" style="width: 5em"></td>
<td valign="middle"><input type="number" name="qty" class="input qty1" value="" style="width: 5em"></td>
<td valign="middle"><input disabled="disabled" id="Gst1" style="width: 6.5em" name="gst"></td>
<td valign="middle"><input disabled="disabled" class="text-right" id="result1" name="result1" class="input result1" value="" style="width: 7.4em"></td>
</tr>
<tr>
<td valign="middle"><input type="number" class="input prec2" value="" style="width: 3em" name="pre"></td>
<td valign="middle"><input type="number" name="rate" class="input rate2" value="" style="width: 5em"></td>
<td valign="middle"><input type="number" name="qty" class="input qty2" value="" style="width: 5em"></td>
<td valign="middle"><input disabled="disabled" id="Gst2" style="width: 6.5em" name="gst2"></td>
<td valign="middle"><input disabled="disabled" class="text-right" id="result2" name="result2" class="input result2" style="width: 7.4em"></td>
</tr>
</tbody>
</table>
</div>
<div class="rowmain">
<div class="leftttext">
<table class="th1">
<tr>
<th>Rupees in Words</th>
<td><textarea id="word" rows="2" cols="60"></textarea></td>
</tr>
</table>
</div>
<div class="righttext">
<table>
<tr>
<th class="thG">Grand Total</th>
<td><input disabled="disabled" class="text1" id="grandT" value="" style="width: 8em"></td>
</tr>
</table>
</div>
</div>
</page>
</body>
</html>
Here is a simple short method to convert numbers to words in English.
//----------------------------------------------------------------
function numToWords(num = 0) {
if (num==0) return "Zero";
num=("0".repeat(2*(num+="").length%3)+num).match(/.{3}/g);
let out="",T1=["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],
T2=["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"],
SC=["","Thousand","Million","Billion","Trillion","Quadrillion"];
return num.forEach((n,i)=>{if(+n){let h=+n[0],t=+n.substring(1),S=SC[num.length-i-1];
out+=(out?" ":"")+(h?T1[h]+" Hundred":"")+(h&&t?" ":"")+(t<20?T1[t]:T2[+n[1]]+(+n[2]?"-":"")+T1[+n[2]]);
out+=(out && S?" ":"")+S;}}),out;}
//----------------------------------------------------------------
console.log(numToWords(0))
console.log(numToWords(22))
console.log(numToWords(1234))
console.log(numToWords(3354646))
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>