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>
Related
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>
I think this should be simple but just can't get it right...I am trying to get row total on a table that has incrementing ids like:
<table id="myTable" class="form">
<thead>
<tr>
....
</tr>
</thead>
<tbody>
<tr class="">
<td>
<input type="number" name="quantity" id="item-0-quantity">
</td>
<td>
<input type="number" name="unit_price"id="item-0-unit_price">
</td>
<td>
<td>
<input type="number" name="quantity" id="item-1-quantity">
</td>
<td>
<input type="number" name="unit_price"id="item-1-unit_price">
</td>
...etc
<td>
</tr>
</tbody>
</table>
I initially used the method below for each row's total calculation and it worked, but it's not efficient.
for first row: $('#item-0-quantity, #item-0-unit-price').on('input',function(e){
$('#Total').val(parseFloat($('#item-0-quantity').val()) * parseFloat($('#item-0-
unit-price').val()));
for second row: $('#item-1-quantity, #item-1-unit-price').on('input',function(e){
$('#Total').val(parseFloat($('#item-1-quantity').val()) * parseFloat($('#item-1-
unit-price').val()));
...and so on.
I thought i would better to use a For Loop to iterate and update the value of i based on a rowCounter like:
var rowCounter = $("#myTable tr").length - 1;
for (var i = 0; i <= rowCounter; i++) {
$('#item-'+i+'-quantity, #item-'+i+'-unit-price').on('input',function(e){
$('#Total').val(parseFloat($('#item-'+i+'-quantity').val()) * parseFloat($('#item-'+i+'-unit-price').val()));
});
}
When i input values(quantity and unit-price), i don't get the total.The For Loop doesn't work. Please help,thanks.
Try this:
//loop by name
$("input[name=quantity], input[name=unit_price]").on('input', function () {
var total = 0;
$("input[name=quantity]").each(function (i, e) {
total += $(this).val() * $(e).closest("tr").find("input[name=unit_price]").val();
});
$('#Total').val(total);
});
//loop by table
$("#myTable input[type=number]").on('input', function () {
var total = 0;
$("#myTable tr").each(function (i, e) {
if (document.getElementById("item-" + i + "-quantity") && document.getElementById("item-" + i + "-unit_price")) {//just check if elements exists
total += $(e).find("#item-" + i + "-quantity").val() * $(e).find("#item-" + i + "-unit_price").val();
}
});
$('#Total_by_table_rows').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="form">
<tbody>
<tr class="">
<td>
<input type="number" name="quantity" id="item-0-quantity">
</td>
<td>
<input type="number" name="unit_price"id="item-0-unit_price">
</td>
</tr>
<tr>
<td>
<input type="number" name="quantity" id="item-1-quantity">
</td>
<td>
<input type="number" name="unit_price"id="item-1-unit_price">
</td>
</tr>
</tbody>
</table>
<label> Total:
<input id="Total">
</label>
<label> Total by table rows:
<input id="Total_by_table_rows">
</label>
Because the content you want to sum is identified with the "quantity" and "unit_price" name attributes, you can use this:
$('tr').each(function() {
sum += $('input[name="quantity"]', this).val() * $('input[name="unit_price"]', this).val();
})
The second parameter in the selector (this in our case) give jQuery a context for the search, i.e., each of the rows of the table.
Here you have the snippet:
$('#calculate').click(function() {
var sum = 0;
$('tr').each(function() {
sum += $('input[name="quantity"]', this).val() * $('input[name="unit_price"]', this).val();
})
$('#result').text(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="form">
<tbody>
<tr>
<td>
<input type="number" name="quantity" value="0">
</td>
<td>
<input type="number" name="unit_price" value="0">
</td>
</tr>
<tr>
<td>
<input type="number" name="quantity" value="0">
</td>
<td>
<input type="number" name="unit_price" value="0">
</td>
</tr>
</tbody>
</table>
<input type="button" value="Calculate" id="calculate">
<div>
Result: <span id="result"></span>
</div>
Here you can do like this.
Your code is not working becuase of
var rowCounter = $("#myTable tr").length - 1;
for (var i = 0; i <= rowCounter; i++) {
$('#item-'+i+'-quantity, #item-'+i+'-unit-price').on('input',function(e){
$('#Total').val(parseFloat($('#item-'+i+'-quantity').val()) * parseFloat($('#item-'+i+'-unit-price').val()));
});
}
For Loop was executes before your type in input fields.
And also you have some mistake in code too like here you wrote $('#item-'+i+'-unit-price') but it should be like this $('#item-'+i+'-unit_price')
var quantity = $("input[name='quantity']");
$("input[name='quantity'], input[name='unit_price']").on('input',function(){
var total = 0;
$(quantity).each(function(){
total += parseFloat($(this).val()) * parseFloat($(this).parent().next().find("input[name='unit_price']").val());
});
$("#Total span").html(total);
});
td {
width: 80%;
float: left;
margin-left: 10px;
}
label {
width: 20%;
float: left
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="form">
<tbody>
<tr class="">
<td>
<label>Quantity 1</label>
<input type="number" name="quantity" id="item-0-quantity" />
</td>
<td>
<label>Unit Price 1</label>
<input type="number" name="unit_price"id="item-0-unit_price" />
</td>
<td>
<label>Quantity 1</label>
<input type="number" name="quantity" id="item-1-quantity" />
</td>
<td>
<label>Unit Price 1</label>
<input type="number" name="unit_price"id="item-1-unit_price" />
</td>
<td id="Total">
<label>Total</label>
<span></span>
</td>
</tr>
</tbody>
</table>
I have this form which is in a foreach loop,
to get the value of the amount input "qty[]" it should be multiply to "uprice[]".
and the last input that is outside the foreach loop, it should display the total sum of all amount.
<tbody>
<?php foreach($_POST['porder'] as $porder): ?>
<tr>
<td>
<input type="text" id="itemnum[]" name="itemnum[]"
max=999 class="form-control form-control-line">
</td>
<td>
<input type="text" id="code[]" name="code[]" class="form-control form-control-line"
value="<?php echo $porder ; ?>"readonly>
</td>
<td>
<input style="text-transform:uppercase" type="text" id="rev"
name="rev[]" class="form-control form-control-line" required>
</td>
<td>
<input style="text-transform:uppercase" type="text" id="desc"
name="desc[]" class="form-control form-control-line" required>
</td>
<td>
<input type="tel" id="qty<?=$porder?>" name="qty[]" min="1"
class="form-control form-control-line" onkeyup="compute('<?=$porder?>')" required>
</td>
<td>
<input type="tel" id="uprice<?=$porder?>" name="uprice[]" min="1"
class="form-control form-control-line" onkeyup="compute('<?=$porder?>')" required>
</td>
<td>
<input type="number" id="amount<?=$porder?>" name="amount[]"
onkeyup="total()" class="form-control form-control-line" >
</td>
</tr>
<?php endforeach ?>
<tr >
<td colspan="5" ></td>
<td><strong>Total
</td>
<td>
<input type="number" id="total" name="total" class="form-control" >
</td>
</tr>
I tried to use a javascript to display the amount and the total. I only get the amount but not the total.
<script>
function compute(id) {
var txtFirstNumberValue = document.getElementById('qty'+id).value;
var txtSecondNumberValue = document.getElementById('uprice'+id).value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('amount'+id).value = result;
}
}
</script>
<script>
function total(){
var amount = document.getElementsByName("amount[]");
var total = 0;
for (var i = 0; i <amount.length; i++) {
var input_value=amount[i];
var signle_value_input = input_value.value;
if(signle_value_input.length!=0)
total +=parseInt(input_value.value);
}
if (!isNaN(total)) {
document.getElementById('total').value = total;
}
}
</script>
The Total doesn't show.
<script>
function total(){
var total = 0;
var amount = document.getElementsByName('amount[]');
for (var i = 0; i <amount.length; i++) {
var inp=amount[i];
var signle_value_input = inp.value;
if(signle_value_input.length!=0)
total +=parseInt(inp.value)
}
if (!isNaN(total)) {
document.getElementById("total").value = total;
}
}
</script>
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>
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