Jquery subtotal function conflicting with js gst function - javascript

O.k today is starting to be 1 step forward and 2 steps back. I have a Jquery function that does the price x qty = subtotal in the form and then each subtotal is calculated into a total, Which is all fine and dandy. I then have a plain js function that took that total value and added the gst and then a further subtotal figure which was created on it's own and works then at this point when i tried to move it over the gst and finial total functions won't work and i can't get any error codes out of it either. At this point i can only assume that the js script can't talk to the Jquery script or something is really wrong.
// Jquery script
<script type="text/javascript">
jQuery(function($) {
$(".qty, .tradeprice").change(function() {
var total = 0;
$(".qty").each(function() {
var $qty = $(this),
$row = $qty.closest('tr'),
$tradePrice = $row.find('.tradeprice'),
$subtotal = $row.find('.subtotal');
subtotal = parseInt($qty.val(), 10) * parseFloat($tradePrice.val());
total += subtotal;
$subtotal.val(subtotal);
});
$('.total').val(total);
}).change();
});
</script>
// JS script
<script type="text/javascript">
function updatePrice() {
// Get the ex-GST price from its form element
var exPrice = document.getElementById("ex-gst").value;
var gstPrice = document.getElementById("gst").value;
// Get the GST price
gstPrice = exPrice * 0.1;
var TPrice = parseInt(gstPrice) + parseInt(exPrice);
// Set the GST price in its form element
document.getElementById("gst").value = gstPrice;
document.getElementById("inc-gst").value = TPrice;
}
</script>
// bottom of HTML
<form>
<table>
<tr>
<th><input type='text' name='po101' id='po101'/></th>
<td><input name='po102' type='text' id="po102"/></td>
<td><input name='po103' type='text' id="po103" /></td>
<td>$<input name='po104' type="text" class='tradeprice' id="po104" value="0" /></td>
<th><input name='po105' type="text" class='qty' id="po105" value="0" /></th>
<td><input name='po106' type='text' class='subtotal' id="po106" readonly="true" /></td>
</tr>
<tr>
<th height='24' colspan="7">Total:<input type='text' id='Total' name='Total' class='total' readonly="true" onChange="updatePrice()"/></th>
</tr>
<tr>
<th height='24' colspan="7"><div id='submit'><input type='submit' /></div></th>
</tr>
<tr>
<th height='24' colspan="7">
<input type='text' id="gst" name='gst' onChange="updatePrice()" />
<input type='text' id="inc-gst" name='inc-gst' onChange="updatePrice(this.form)"/>
</th>
</tr>
</table>
</form>

I have now edited you code, and changed this line
var exPrice = document.getElementById("ex-gst").value;
to
var exPrice = document.getElementById("Total").value;
I have also updated the code by removing onChange() from HTML and added the trigger for your updatePrice() function to the change event.
And then this is the result (I have also added the jQuery version as comments, both will work).
jQuery(function($) {
$(".qty, .tradeprice").change(function() {
var total = 0;
$(".qty").each(function() {
var $qty = $(this),
$row = $qty.closest('tr'),
$tradePrice = $row.find('.tradeprice'),
$subtotal = $row.find('.subtotal');
subtotal = parseInt($qty.val(), 10) * parseFloat($tradePrice.val());
total += subtotal;
$subtotal.val(subtotal);
});
$('.total').val(total);
updatePrice();
}).change();
});
function updatePrice() {
// Get the ex-GST price from its form element
var exPrice = document.getElementById("Total").value;
//var exPrice = $('#Total').val() //this is jQuery
var gstPrice = document.getElementById("gst").value;
//var exPrice = $('#gst').val() //this is jQuery
// Get the GST price
gstPrice = exPrice * 0.1;
var TPrice = parseInt(gstPrice) + parseInt(exPrice);
// Set the GST price in its form element
document.getElementById("gst").value = gstPrice;
//$('#gst').val(gstPrice) //this is jQuery
document.getElementById("inc-gst").value = TPrice;
//$('#inc-gst').val(TPrice) //this is jQuery
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<table>
<tr>
<th>
<input type='text' name='po101' id='po101' />
</th>
<td>
<input name='po102' type='text' id="po102" />
</td>
<td>
<input name='po103' type='text' id="po103" />
</td>
<td>$
<input name='po104' type="text" class='tradeprice' id="po104" value="0" />
</td>
<th>
<input name='po105' type="text" class='qty' id="po105" value="0" />
</th>
<td>
<input name='po106' type='text' class='subtotal' id="po106" readonly="true" />
</td>
</tr>
<tr>
<th height='24' colspan="7">Total:
<input type='text' id='Total' name='Total' class='total' readonly="true" />
</th>
</tr>
<tr>
<th height='24' colspan="7">
<div id='submit'>
<input type='submit' />
</div>
</th>
</tr>
<tr>
<th height='24' colspan="7">
<input type='text' id="gst" name='gst' />
<input type='text' id="inc-gst" name='inc-gst' />
</th>
</tr>
</table>
</form>

Related

Use JavaScript to get value of the for each

I'm new using JavaScript. I need to get the value ${prdcts.precioUnidad} of the checked line. The idea is to set the total price in a dynamic way, so when the user checks or unchecks each line the value of total either adds the new value when checked, or subtracts the previous value when unchecked.
I tried to get the value using the getElement() methods, but I don't know how to access the value of the variable within that specific row.
This is the HTML:
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ventas</title>
</head>
<body>
<center><h1>Venta de Productos</h1>
<form action="venta.htm" method="post">
<table id="tableID" border="4">
<tbody><tr>
<th>ID</th>
<th>Nombre</th>
<th>Valor</th>
<th>Comprado</th>
</tr>
<tr>
<td>2</td>
<td>Chupetin</td>
<td>5.0</td>
<td><input name="check" type="checkbox" value="2" label="2" path="prdcts"></td>
</tr>
<tr>
<td>3</td>
<td>Alfajor DDL</td>
<td>30.0</td>
<td><input name="check" type="checkbox" value="3" label="3" path="prdcts"></td>
</tr>
<tr>
<td>4</td>
<td>Sanguche Mila</td>
<td>60.0</td>
<td><input name="check" type="checkbox" value="4" label="4" path="prdcts"></td>
</tr>
</tbody></table>
<br>
<br>
<br>
<table border="4">
<tbody><tr>
<td>Total Compra: <input name="total" id="total" type="number" readonly="" value="0"></td>
</tr>
<tr>
<td>Monto Pagado: <input name="monto" id="monto" type="number" value="0"></td>
</tr>
<tr>
<td>Vuelto: <input name="vuelto" id="vuelto" type="number" readonly="" value="0"></td>
</tr>
<tr>
<td><input name="begin" onclick="calcularVuelto()" type="button" value="Calcular Vuelto"></td>
</tr>
</tbody></table>
<br>
<br>
<input name="clear" onclick="window.location.href = 'venta.htm'" type="button" value="Borrar venta">
<input name="begin" onclick="window.location.href = 'principal.htm'" type="button" value="Inicio">
<input name="confirm" type="submit" value="Confirmar Venta">
<br>
</form>
</center>
<script>
// Make it an Array with "Array.from" so we can use reduce() on it
var $$checkboxes = Array.from(document.querySelectorAll('input[name=check]')),
$total = document.getElementById('total');
// For each checkbox
$$checkboxes.forEach(function ($checkbox) {
// When its value changes, update total
$checkbox.addEventListener('change', updateTotal);
});
function updateTotal() {
// For each checkbox
alert("aca");
var total = $$checkboxes.reduce(function (sum, $checkbox) {
// If it's checked
alert("aca2")
if ($checkbox.checked) {
var price = $checkbox.parentNode.parentNode // parent <tr>
.querySelectorAll('td')[2].innerText.trim(); // remove spaces
// Add price to the sum
return sum + parseFloat(price);
} else {
// If it's not checked, just return the current sum
return sum;
}
}, 0);
$total.value = total.toFixed(2); // Always 2 decimals
}
function calcularVuelto() {
var total = document.getElementById("total").value;
var pago = document.getElementById("monto").value;
var fTotal = parseFloat(total);
var fPago = parseFloat(pago);
totalResta = fPago - fTotal;
document.getElementById("vuelto").value = totalResta;
}
</script>
</body></html>
You can use Array.prototype.reduce() to calculate the total:
// Make it an Array with "[].slice.call" so we can use reduce() on it
var $$checkboxes = [].slice.call(document.querySelectorAll('input[name=check]')),
$total = document.getElementById('total');
// For each checkbox
$$checkboxes.forEach(function ($checkbox) {
// When its value changes, update total
$checkbox.addEventListener('change', updateTotal);
});
function updateTotal() {
// For each checkbox
var total = $$checkboxes.reduce(function (sum, $checkbox) {
// If it's checked
if ($checkbox.checked) {
var price = $checkbox.parentNode.parentNode // parent <tr>
.querySelectorAll('td')[2].innerText.trim(); // remove spaces
// Add price to the sum
return sum + parseFloat(price);
} else {
// If it's not checked, just return the current sum
return sum;
}
}, 0);
$total.value = total.toFixed(2); // Always 2 decimals
}
<table border="4">
<tr><th>ID</th> <th>Nombre</th> <th>Valor</th> <th>Comprado</th> </tr>
<tr><td>x</td><td>X</td><td>5.99</td><td><input name="check" type="checkbox" value="x" label="X"/></td></tr>
<tr><td>y</td><td>Y</td><td>3.95</td><td><input name="check" type="checkbox" value="y" label="Y"/></td></tr>
<tr><td>z</td><td>Z</td><td>14.20</td><td><input name="check" type="checkbox" value="z" label="Z"/></td></tr>
</table>
<p>Total Compra: <input name="total" id="total" type="number" value="0" readonly/></p>
The checked flag is either on or off. It doesn't take an argument. So it looks like
<input type="checkbox" name="name" checked> checked </input>
<br/>
<input type="checkbox" name="name"> unchecked</input>
In your code you'll need something like: ${prdcts.idProducto ? "checked" : ""}

calculate salesperson's sales + commission from an html form user fills out/text input

The user fills out the form below based upon how many of the items they sold.
The calculator then calculates how much the salesperson sold into the blanks below + how much they earned + 200 dollars additional + 9% commission on total sales... and then the form outputs the results.
round the outputted results to 2 decimal places.
check for valid numeric input
make sure the number of items sold is < 0, as nobody sells negative number of items.
right-justify all amounts.
I have written out what I think the functions should be about, without proper syntax. I am super green with javascript and pretty much am only good at HTML sadly. I need help making what I have correspond to the form fields properly... this is all very overwhelming. Any Explanation is helpful.
<h1>Sales Commission Calculator</h1>
<hr>
<section>
<form name="salesperson_total">
Salesperson: <input type="text" title="Please make sure that the salesperson's name is spelled correctly" name="sp" size="20">
<br>
<br>
<h3>Input the number of items sold for each item number:</h3>
Item 1: <input class="t" type="text" name="num_item1" size="8" value="num_item1"><br>
Item 2: <input class="t" type="text" name="num_item2" size="8" value="num_item2"><br>
Item 3: <input class="t" type="text" name="num_item3" size="8" value="num_item3"><br>
Item 4: <input class="t" type="text" name="num_item4" size="8" value="num_item4"><br><br>
<input type="button" value="Submit">
<input type="reset" value="Reset"><br><br>
<table>
<tr>
<th>Item #</th>
<th>Price</th>
<th>Number Sold</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td>$239.99</td>
<td><input type="text" class="t" name="int_item1"></td>
<td><input type="text" class="t" name="total_item1"></td>
</tr>
<tr>
<td>2</td>
<td>$129.75</td>
<td><input type="text" class="t" name="int_item2"></td>
<td><input type="text" class="t" name="total_item2"></td>
</tr>
<tr>
<td>3</td>
<td>$99.95</td>
<td><input type="text" class="t" name="int_item3"></td>
<td><input type="text" class="t" name="total_item3"></td>
</tr>
<tr>
<td>4</td>
<td>$350.89</td>
<td><input type="text" class="t" name="int_item4"></td>
<td><input type="text" class="t" name="total_item4"></td>
</tr>
<tr>
<td colspan="3">Total Amount Sold:</td>
<td><input type="text" class="t" name="final_total"></td>
</tr>
<tr>
<td colspan="3">Total Weekly Earnings:</td>
<td><input type="text" class="t" name="salary"></td>
</tr>
</table>
</form>
</section>
<br>
<script>
var num_item1 = "";
var num_item2 = "";
var num_item3 = "";
var num_item4 = "";
var price1 = 239.99;
var price2 = 129.75;
var price3 = 99.95;
var price4 = 350.89;
var int_item1 = "";
var int_item2 = "";
var int_item3 = "";
var int_item4 = "";
var total_item1;
var total_item2;
var total_item3;
var total_item4;
var comm;
function numberSold() {
num_item1
num_item2
num_item3
num_item4
}
function totalSold() {
total_item1 = num_item1 * price1;
total_item2 = num_item2 * price2;
total_item3 = num_item3 * price3;
total_item4 = num_item4 * price4;
}
function amountSold() {
total_item1 + total_item2 + total_item3 + total_item4;
}
function getComm() {
comm = Math.floor(9/amountSold*100);
}
function weeklyEarned() {
amountSold + comm + 200
document.write();
}
</script>
</section>
</body>
</html>
//see above for expected results in description.
I did this quickly and this should suffice to act as a guide:
<h1>Sales Commission Calculator</h1>
<hr>
<section>
<form name="salesperson_total">
Salesperson: <input type="text" title="Please make sure that the salesperson's name is spelled correctly" name="sp" size="20">
<br>
<br>
<h3>Input the number of items sold for each item number:</h3>
Item 1: <input class="t" type="text" name="num_item1" id="item1" size="8" value="0" style="text-align:right;" onkeyup="checkNumItems();"><br>
Item 2: <input class="t" type="text" name="num_item2" id="item2" size="8" value="0" style="text-align:right;" onkeyup="checkNumItems();"><br>
Item 3: <input class="t" type="text" name="num_item3" id="item3" size="8" value="0" style="text-align:right;" onkeyup="checkNumItems();"><br>
Item 4: <input class="t" type="text" name="num_item4" id="item4" size="8" value="0" style="text-align:right;" onkeyup="checkNumItems();"><br>
<span id="msg" style="color:red;"></span><br><br> <!--This element is used to display an error message if any item entered is less than zero-->
<input type="button" value="Submit" id="submitBtn" onclick="calculate()">
<input type="reset" value="Reset" onclick="reset()"><br><br>
<table>
<tr>
<th>Item #</th>
<th>Price</th>
<th>Number Sold</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td>$239.99</td>
<td><input type="text" class="t" name="int_item1" id="int_item1" style="text-align:right;"></td>
<td><input type="text" class="t" name="total_item1" id="total_item1" style="text-align:right;"></td>
</tr>
<tr>
<td>2</td>
<td>$129.75</td>
<td><input type="text" class="t" name="int_item2" id="int_item2" style="text-align:right;"></td>
<td><input type="text" class="t" name="total_item2" id="total_item2" style="text-align:right;"></td>
</tr>
<tr>
<td>3</td>
<td>$99.95</td>
<td><input type="text" class="t" name="int_item3" id="int_item3" style="text-align:right;"></td>
<td><input type="text" class="t" name="total_item3" id="total_item3" style="text-align:right;"></td>
</tr>
<tr>
<td>4</td>
<td>$350.89</td>
<td><input type="text" class="t" name="int_item4" id="int_item4" style="text-align:right;"></td>
<td><input type="text" class="t" name="total_item4" id="total_item4" style="text-align:right;"></td>
</tr>
<tr>
<td colspan="3">Total Amount Sold:</td>
<td><input type="text" class="t" name="final_total" id="final_total" style="text-align:right;"></td>
</tr>
<tr>
<td colspan="3">Total Weekly Earnings:</td>
<td><input type="text" class="t" name="salary" id="salary" style="text-align:right;"></td>
</tr>
</table>
</form>
</section>
<br>
<!--Javascript-->
<script>
//Declare and initialize all variables
var num_item1 = "";
var num_item2 = "";
var num_item3 = "";
var num_item4 = "";
var price1 = 239.99;
var price2 = 129.75;
var price3 = 99.95;
var price4 = 350.89;
var int_item1 = "";
var int_item2 = "";
var int_item3 = "";
var int_item4 = "";
var total_item1 = 0;
var total_item2 = 0;
var total_item3 = 0;
var total_item4 = 0;
var comm = 0;
var earnings = 0;
//As the user enters a value in the item fields check if the number of items entered by the user is less than zero
function checkNumItems(){
if(document.getElementById('item1').value < 0 || document.getElementById('item2').value < 0 || document.getElementById('item3').value < 0 || document.getElementById('item4').value < 0){
//Display an error message if either one of the items is less than zero
document.getElementById('msg').innerHTML = "Error: Values cannot be less than 0";
//Disable the submit button if either one of the items is less than zero
document.getElementById("submitBtn").disabled = true;
}else{
//Remove (or do not display) an error message if all items are more than 0
document.getElementById('msg').innerHTML = "";
//Enable submit button if all items are greater than zero
document.getElementById("submitBtn").disabled = false;
} }
//Function used to calculate and fill in all fields when the user press Submit
function calculate(){
//Get the values the user entered
num_item1 = document.getElementById('item1').value;
num_item2 = document.getElementById('item2').value;
num_item3 = document.getElementById('item3').value;
num_item4 = document.getElementById('item4').value;
//Set the values into the fields of the column 'Number Sold'
document.getElementById('int_item1').value = num_item1;
document.getElementById('int_item2').value = num_item2;
document.getElementById('int_item3').value = num_item3;
document.getElementById('int_item4').value = num_item4;
//Calculate the total for each item
total_item1 = num_item1 * price1;
total_item2 = num_item2 * price2;
total_item3 = num_item3 * price3;
total_item4 = num_item4 * price4;
//Set the total for each fields of the 'Total' column
document.getElementById('total_item1').value = total_item1;
document.getElementById('total_item2').value = total_item2;
document.getElementById('total_item3').value = total_item3;
document.getElementById('total_item4').value = total_item4;
//Calculate the 'Total Amount Sold' field
amountSold = total_item1 + total_item2 + total_item3 + total_item4;
//Set (fill in) the 'Total Amount Sold' field
document.getElementById('final_total').value = amountSold;
//Calculate the commission
comm = Math.floor(9/amountSold*100);
//Caclulate the earnings
earnings = amountSold + comm + 200;
//Set the 'Total Weekly Earnings' field
document.getElementById('salary').value = earnings;
}
//Function used to Reset the fields the salesperson enters when they press Reset
function reset(){
document.getElementById('item1').value = 0;
document.getElementById('item2').value = 0;
document.getElementById('item3').value = 0;
document.getElementById('item4').value = 0;
}
</script>

Calculate values from multiple number fileds - Jquery

I am trying to calculate price based on quantity and price and calculating a subtotal by adding all products prices.
below is the code of html
<tr>
<td>
<input min="0" data-unit-price="9.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<input min="0" data-unit-price="19.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<h3><span class="se-curency">$</span><span data-sub-total="0" id="se-sub-total" class="se-total-amount">0</span></h3>
<h3><span class="se-curency">$</span><span id="se-vat" class="se-total-amount">8</span></h3>
</td>
</tr>
And I am trying The below js
jQuery( document ).on( 'input', '.se-ticket-qty', function() {
var sum = 0;
jQuery(this).each(function(i){
var unit_price = jQuery(this).data('unit-price');
var amount = jQuery(this).val();
var current_sub_total = parseFloat(unit_price);
sum += current_sub_total;
var sub_total = jQuery('#se-sub-total').attr('data-sub-total');
var final_sub_total = parseFloat(sub_total) + sum;
jQuery('#se-sub-total').attr('data-sub-total', final_sub_total.toFixed(2));
jQuery('#se-sub-total').html(final_sub_total.toFixed(2));
});
console.log(sum);
});
But There is an error in calculating.The sub total is working fine if I use upper arrow in number field.But if i use below arrow or input an number by manually it is not working.
It looks like you just had a few small issues with how you were using each logic and adding up the totals. Here is a snippet that does what I think you were trying to do. Just un-comment the console.logs to see how the order of operations changed how the final sum is calculated. I am not sure what you wanted with the second display with 8$:
// Shorthand for $( document ).ready()
$(function() {
console.log( "ready!" );
$(document).on('input', '.se-ticket-qty', function(){
CalculateTotal();
});
});
function CalculateTotal(){
var sum = 0;
$(".tableWithInputs").find( ".se-ticket-qty" ).each(function( index ){
var unit_price = parseFloat($(this).data('unit-price'));
var amount = parseFloat($(this).val());
var totalPrice = unit_price * amount;
//console.log("unit_price: " + unit_price);
//console.log("unit_price: " + unit_price);
//console.log("amount: " + amount);
//console.log("totalPrice: " + totalPrice);
sum += parseFloat(totalPrice);
});
$('#se-sub-total').attr('data-sub-total', sum.toFixed(2));
$('#se-sub-total').text(sum.toFixed(2));
//console.log(sum.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tableWithInputs">
<tr>
<td>
<input min="0" data-unit-price="9.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<input min="0" data-unit-price="19.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<h3><span class="se-curency">$</span><span data-sub-total="0" id="se-sub-total" class="se-total-amount">0</span></h3>
<h3><span class="se-curency">$</span><span id="se-vat" class="se-total-amount">8</span></h3>
</td>
</tr>
</table>

calculate grand total with javascript

I don't know how to get Grand total value
grand total is sum of all total
here is the code
<?php
$con = mysqli_connect('localhost', 'root', '', 'a.karat');
if(isset($_POST['product_id']))
{
$prno=$_POST['prno'];
$i=1;
$sql = mysqli_query($con,"select * from detail_pr where prNo='$prno'");
while ($r = mysqli_fetch_array($sql)) {
echo
'<tr>
<td><input type="checkbox" name="check[]" id="check'.$i.'" value="'.$i.'"></td>
<td><label for="productCode"></label>
<input type="text" name="productCode'.$i.'" id="productCode'.$i.'" readonly value="'.$r["productCode"].'" size="12" ></td>
<td><label for="productName"></label>
<input type="text" name="productName'.$i.'" id="productName'.$i.'" readonly value="'.$r["productName"].'"size="35" ></td>
<td><label for="qty"></label>
<input type="number" onkeyup="calc(this);" name="qty'.$i.'" id="qty'.$i.'" readonly value="'.$r["qty"].'" size="8" ></td>
<td><input type="number" onkeyup="calc(this);" name="price'.$i.'" id="price'.$i.'" size="10" min="1" max="99" onchange="calc(this);" ></td>
<td><input type="number" onkeyup="calc(this);" name="discount'.$i.'" id="discount'.$i.'" size="10" min="0" max="99" onchange="calc(this);"></td>
<td><input type="number" name="total'.$i.'" id="total'.$i.'" size="10" min="1" max="99" onchange="calc(this);" ></td>
</tr>';
$i++;
}
}
?>
<table width="400" border="0" align="right">
<tr>
<th scope="row">Grand Total</th>
<td>:</td>
<td><input name="grandtotal" id="grandtotal" type="text"></td>
</tr>
</table>
<script>
function calc(id) {
var row = id.parentNode.parentNode;
var quant = row.cells[3].getElementsByTagName('input')[0].value;
var price = row.cells[4].getElementsByTagName('input')[0].value;
var disc = row.cells[5].getElementsByTagName('input')[0].value;
if (disc == null || disc == '') {
res = parseFloat(quant) * parseFloat(price);
} else {
var res = (parseFloat(quant) * parseFloat(price)) - (parseFloat(quant) * parseFloat(price) * (parseFloat(disc) / 100));
}
row.cells[6].getElementsByTagName('input')[0].value = res;
}
</script>
I have manage to calculate total per row
now I need your help to sum all total and put the value in the grandtotal textbox
I guess on every change of a value of one of your input elements in your form the grand total should be updated, right? I 'd place an event listener on the form tag to keep it simple.
<form id="your-form" method="post" action="">
<!-- All your other inputs here -->
<input type="text" name="grandtotal" id="grandtotal">
</form>
<script>
document.querySelector('#your-form').addEventListener('change', function( event ) {
if (event.target.id && event.target.id !== 'grandtotal') {
var allTotals = document.querySelectorAll('input[name^="total"]'),
allTotalSum = 0;
Array.prototype.forEach.call(allTotals, function( element ) {
if (element.value) {
allTotalSum += parseFloat(element.value);
}
});
document.querySelector('#grandtotal').value = allTotalSum;
}
});
</script>
So on every change of one of your input fields the sum is updated. This code is untested.

Why does the total from last row is not calculating the sum?

I am doing a project that involves making an estimate and adding up does results. I am using the method GET and using some of the the info from the url. Also i am using WordPress to build the Web Page. Problem is that sum of the TOTAL column is not working and showing in the TOTAL row that i made. Is not an error but i think I need to add one more piece of code or change something in the javascript. So why does the id:"total" not showing the sum of the whole column? is the total.value wrong? does the id:"system_total" have a problem?
Here is how the HTML looks like:
<form >
<h2>Cotizacion</h2>
<table class="Cotization">
<tbody>
<tr>
<th style="width:25%;font-size:16px;text-align:center;">Description</th>
<th style="width:15%;" class="qtyhd" title="qtytt">Qty</th>
<th style="width:15%;" class="ratehd" title="ratett">Rate</th>
<th style="width:15%;" class="tlhd" title="totaltt">Total</th>
</tr>
<tr>
<td>PV Grid Tied System</td>
<td> <input id="system_qty" name="system_qty" value="1" type="number" /></td>
<td> <input id="system_rate" name="system_rate" value="0" type="number" /></td>
<td> <output id="system_total"> </output></td>
</tr>
<tr>
<td>Solar Modules 250w</td>
<td> <input id="modules_qty" name="modules_qty" value="0" type="number" /></td>
<td> <input id="modules_rate" name="modules_rate" value="0" type="number" /></td>
<td> <output id="modules_total"> </output></td>
</tr>
<tr>
<td>Inverter</td>
<td> <input id="inverter_qty" name="inverter_qty" value="1" type="number" /></td>
<td> <input id="inverter_rate" name="inverter_rate" value="0" type="number" /></td>
<td> <output id="inverter_total"> </output></td>
</tr>
<tr>
<td>Aluminum Fames</td>
<td> <input id="aluminum_qty" name="aluminum_qty" value="0" type="number" /></td>
<td> <input id="aluminum_rate" name="aluminum_rate" value="0" type="number" /></td>
<td> <output id="aluminum_total"> </output></td>
</tr>
<tr>
<td>Service Disconnect</td>
<td> <input id="servicedt_qty" name="servicedt_qty" value="1" type="number" /></td>
<td> <input id="servicedt_rate" name="servicedt_rate" value="0" type="number" /></td>
<td> <output id="servicedt_total"> </output></td>
</tr>
<tr>
<td>Installation</td>
<td> <input id="installation_qty" name="installation_qty" value="1" type="number" /></td>
<td> <input id="installation_rate" name="installation_rate" value="0" type="number" /></td>
<td> <output id="installation_total"> </output></td>
</tr>
<tr>
<td>Down Payment</td>
<td> <input id="dnpayment_qty" name="dnpayment_qty" value="-1" type="number" /></td>
<td> <input id="dnpayment_rate" name="dnpayment_rate" value="0" type="number" /></td>
<td> <output id="dnpayment_total"> </output></td>
</tr>
<tr>
<td>Total </td>
<td> </td>
<td> </td>
<td> <input id="total" name="total"/></td>
</tr>
</tbody>
</table>
</form>
And here is the javascript that might have the problem:
<script>
document.addEventListener('DOMContentLoaded', function () {
var system_size = Number(getParameterByName('system_size'));
var system_rate_input = document.getElementById('system_rate');
var modules_qty = document.getElementById('modules_qty');
var aluminum_qty = document.getElementById('aluminum_qty');
var systemTotal = Number(document.getElementById('system_total').innerText);
var moduleTotal = Number(document.getElementById('modules_total').innerText);
var inverterTotal = Number(document.getElementById('inverter_total').innerText);
var aluminumTotal = Number(document.getElementById('aluminum_total').innerText);
var servicedtTotal = Number(document.getElementById('servicedt_total').innerText);
var installationTotal = Number(document.getElementById('installation_total').innerText);
var dnpaymentTotal = Number(document.getElementById('dnpayment_total').innerText);
var total = document.getElementById('total');
modules_qty.value = Number(system_size) * 4;
aluminum_qty.value = Number(modules_qty.value);
system_rate_input.value = 2.9 * 1000 * 1.2 * system_size;
updateSystemTotal()
updateModulesTotal()
updateInverterTotal()
updateAluminumTotal()
updateServiceTotal()
updateInstallationTotal()
updateDownPaymentTotal()
total.value = Number(systemTotal) + Number(moduleTotal) + Number(inverterTotal) + Number(aluminumTotal) + Number(servicedtTotal) + Number(installationTotal) + Number(dnpaymentTotal);
})
// FIRST ROW
function updateSystemTotal() {
var output = document.getElementById('system_total');
var quantity = Number(document.getElementById('system_qty').value);
var system_rate = Number(document.getElementById('system_rate').value);
output.innerText = quantity * system_rate;
}
document.getElementById('system_rate').addEventListener('change', updateSystemTotal)
document.getElementById('system_qty').addEventListener('change', updateSystemTotal)
// Second ROW
function updateModulesTotal() {
var output = document.getElementById('modules_total');
var quantity = Number(document.getElementById('modules_qty').value);
var modules_rate = Number(document.getElementById('modules_rate').value);
output.innerText = quantity * modules_rate;
}
document.getElementById('modules_rate').addEventListener('change', updateModulesTotal)
document.getElementById('modules_qty').addEventListener('change', updateModulesTotal)
// Third ROW
function updateInverterTotal() {
var output = document.getElementById('inverter_total');
var quantity = Number(document.getElementById('inverter_qty').value);
var inverter_rate = Number(document.getElementById('inverter_rate').value);
output.innerText = quantity * inverter_rate;
}
document.getElementById('inverter_rate').addEventListener('change', updateInverterTotal)
document.getElementById('inverter_qty').addEventListener('change', updateInverterTotal)
// Fourth ROW
function updateAluminumTotal() {
var output = document.getElementById('aluminum_total');
var quantity = Number(document.getElementById('aluminum_qty').value);
var aluminum_rate = Number(document.getElementById('aluminum_rate').value);
output.innerText = quantity * aluminum_rate;
}
document.getElementById('aluminum_rate').addEventListener('change', updateAluminumTotal)
document.getElementById('aluminum_qty').addEventListener('change', updateAluminumTotal)
// Fith ROW
function updateServiceTotal() {
var output = document.getElementById('servicedt_total');
var quantity = Number(document.getElementById('servicedt_qty').value);
var servicedt_rate = Number(document.getElementById('servicedt_rate').value);
output.innerText = quantity * servicedt_rate;
}
document.getElementById('servicedt_rate').addEventListener('change', updateServiceTotal)
document.getElementById('servicedt_qty').addEventListener('change', updateServiceTotal)
// Six ROW
function updateInstallationTotal() {
var output = document.getElementById('installation_total');
var quantity = Number(document.getElementById('installation_qty').value);
var installation_rate = Number(document.getElementById('installation_rate').value);
output.innerText = quantity * installation_rate;
}
document.getElementById('installation_rate').addEventListener('change', updateInstallationTotal)
document.getElementById('installation_qty').addEventListener('change', updateInstallationTotal)
//Seventh ROW
function updateDownPaymentTotal() {
var output = document.getElementById('dnpayment_total');
var quantity = Number(document.getElementById('dnpayment_qty').value);
var dnpayment_rate = Number(document.getElementById('dnpayment_rate').value);
output.innerText = quantity * dtpayment_rate;
}
document.getElementById('dnpayment_rate').addEventListener('change', updateDownPaymentTotal)
document.getElementById('dnpayment_qty').addEventListener('change', updateDownPaymentTotal)
// DON't TOUCH ANYTHING BELOW THIS POINT!!!
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
</script>
var systemTotal = Number(document.getElementById('system').innerText);
There is no element called "system" in the snippets you provided. Are you sure you don't need to get the value from "system_total"?
Edit:
Total is showing 0 at the beginning, because the subtotals aren't initialized. To fix this, you can use your update functions before calculating the total.
document.addEventListener('DOMContentLoaded', function () {
var system_size = Number(getParameterByName('system_size'));
var system_rate_input = document.getElementById('system_rate');
var modules_qty = document.getElementById('modules_qty');
var aluminum_qty = document.getElementById('aluminum_qty');
var total = document.getElementById('total');
modules_qty.value = Number(system_size) * 4;
aluminum_qty.value = Number(modules_qty.value);
system_rate_input.value = 2.9 * 1000 * 1.2 * system_size;
updateSystemTotal();
updateModulesTotal();
updateInverterTotal();
updateAluminumTotal();
updateServiceTotal();
updateInstallationTotal();
updateDownPaymentTotal();
updateTotal();
})
function updateTotal() {
var total = document.getElementById('total');
var systemTotal = Number(document.getElementById('system_total').innerText);
var moduleTotal = Number(document.getElementById('modules_total').innerText);
var inverterTotal = Number(document.getElementById('inverter_total').innerText);
var aluminumTotal = Number(document.getElementById('aluminum_total').innerText);
var servicedtTotal = Number(document.getElementById('servicedt_total').innerText);
var installationTotal = Number(document.getElementById('installation_total').innerText);
var dnpaymentTotal = Number(document.getElementById('dnpayment_total').innerText);
total.value = Number(systemTotal) + Number(moduleTotal) + Number(inverterTotal) + Number(aluminumTotal) + Number(servicedtTotal) + Number(installationTotal) + Number(dnpaymentTotal);
}
Further, you are updating the subtotals as soon as the user edits Quantities or Rates, but you are not updating the "Total" value.
You could call updateTotal() in your own update functions to solve this issue:
function updateSystemTotal() {
var output = document.getElementById('system_total');
var quantity = Number(document.getElementById('system_qty').value);
var system_rate = Number(document.getElementById('system_rate').value);
output.innerText = quantity * system_rate;
updateTotal();
}
Copy my code and Run it :
javascript(1.js) :
function rr() {
var system_size = document.getElementById('system_qty').value;
var system_rate_input = document.getElementById('system_rate').value;
var modules_qty = document.getElementById('modules_qty').value;
var modules_rate = document.getElementById('modules_rate').value;
var inverter_qty = document.getElementById('inverter_qty').value;
var inverter_rate = document.getElementById('inverter_rate').value;
var aluminum_qty = document.getElementById('aluminum_qty').value;
var aluminum_rate = document.getElementById('aluminum_rate').value;
var servicedt_qty = document.getElementById('servicedt_qty').value;
var servicedt_rate = document.getElementById('servicedt_rate').value;
var installation_qty = document.getElementById('installation_qty').value;
var installation_rate = document.getElementById('installation_rate').value;
var dnpayment_qty = document.getElementById('dnpayment_qty').value;
var dnpayment_rate = document.getElementById('dnpayment_rate').value;
var systemTotal = system_size * system_rate_input;
document.getElementById('system_total').innerHTML = systemTotal;
var moduleTotal = modules_rate * modules_qty;
document.getElementById('modules_total').innerHTML = moduleTotal;
var inverterTotal = inverter_qty * inverter_rate;
document.getElementById('inverter_total').innerHTML = inverterTotal;
var aluminumTotal =aluminum_qty * aluminum_rate;
document.getElementById('aluminum_total').innerHTML = aluminumTotal;
var servicedtTotal = servicedt_qty * servicedt_rate;
document.getElementById('servicedt_total').innerHTML = servicedtTotal;
var installationTotal = installation_qty * installation_rate;
document.getElementById('installation_total').innerHTML = installationTotal;
var dnpaymentTotal = dnpayment_qty * dnpayment_rate;
document.getElementById('dnpayment_total').innerHTML = dnpaymentTotal;
var Total = document.getElementById('total');
aluminum_qty = system_size * 4;
system_rate_input = 2.9 * 1000 * 1.2 * system_size;
Total.value = systemTotal + moduleTotal + inverterTotal+ aluminumTotal + servicedtTotal+ installationTotal + dnpaymentTotal;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="1.js"></script>
<form name="frm" >
<h2>Cotizacion</h2>
<table class="Cotization">
<tbody>
<tr>
<th style="width:25%;font-size:16px;text-align:center;">Description</th>
<th style="width:15%;" class="qtyhd" title="qtytt">Qty</th>
<th style="width:15%;" class="ratehd" title="ratett">Rate</th>
<th style="width:15%;" class="tlhd" title="totaltt">Total</th>
</tr>
<tr>
<td>PV Grid Tied System</td>
<td> <input id="system_qty" name="system_qty" value="1" type="number" /></td>
<td> <input id="system_rate" name="system_rate" value="0" type="number" /></td>
<td> <output id="system_total"> </output></td>
</tr>
<tr>
<td>Solar Modules 250w</td>
<td> <input id="modules_qty" name="modules_qty" value="0" type="number" /></td>
<td> <input id="modules_rate" name="modules_rate" value="0" type="number" /></td>
<td> <output id="modules_total"> </output></td>
</tr>
<tr>
<td>Inverter</td>
<td> <input id="inverter_qty" name="inverter_qty" value="1" type="number" /></td>
<td> <input id="inverter_rate" name="inverter_rate" value="0" type="number" /></td>
<td> <output id="inverter_total"> </output></td>
</tr>
<tr>
<td>Aluminum Fames</td>
<td> <input id="aluminum_qty" name="aluminum_qty" value="0" type="number" /></td>
<td> <input id="aluminum_rate" name="aluminum_rate" value="0" type="number" /></td>
<td> <output id="aluminum_total"> </output></td>
</tr>
<tr>
<td>Service Disconnect</td>
<td> <input id="servicedt_qty" name="servicedt_qty" value="1" type="number" /></td>
<td> <input id="servicedt_rate" name="servicedt_rate" value="0" type="number" /></td>
<td> <output id="servicedt_total"> </output></td>
</tr>
<tr>
<td>Installation</td>
<td> <input id="installation_qty" name="installation_qty" value="1" type="number" /></td>
<td> <input id="installation_rate" name="installation_rate" value="0" type="number" /></td>
<td> <output id="installation_total"> </output></td>
</tr>
<tr>
<td>Down Payment</td>
<td> <input id="dnpayment_qty" name="dnpayment_qty" value="-1" type="number" /></td>
<td> <input id="dnpayment_rate" name="dnpayment_rate" value="0" type="number" /></td>
<td> <output id="dnpayment_total"> </output></td>
</tr>
<tr>
<td>Total </td>
<td> </td>
<td> </td>
<td> <input value="" id="total" name="total"/></td>
</tr>
</tbody>
</table>
</form>
<button id="btn" onclick="rr()">Click</button>
</body>
</html>

Categories

Resources