I need to write a javascript to make certain calculations by taking data from a form. I have written the script and ensured all the ids and variables are correct. For some reason, my script doesn't seem to run. Can someone please tell me where I'm going wrong??
This is my form action.
<body>
<div class="header">
Financial Calculator
</div>
<script type="text/javascript" src="calc.js"></script>
<div class="calc">
<form name="calc" method="post" onsubmit="calc()">
<table align="center">
<tr>
<th></th>
<th>Lease Data</th>
<th>Purchase Data</th>
<th>Purchase Data with Rebate</th>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="cost1" placeholder="Please enter in $"></td>
<td><input type="text" name="cost2" placeholder="Please enter in $"></td>
<td><input type="text" name="cost3" placeholder="Please enter in $"></td>
</tr>
<tr>
<td>Downpayment</td>
<td><input type="text" name="downpayment1" placeholder="Please enter in $"></td>
<td><input type="text" name="downpayment2" placeholder="Please enter in $"></td>
<td><input type="text" name="downpayment3" placeholder="Please enter in $"></td>
</tr>
<tr>
<td>Period</td>
<td><input type="text" name="period1" placeholder="Please enter in months"></td>
<td><input type="text" name="period2" placeholder="Please enter in years"></td>
<td><input type="text" name="period3" placeholder="Please enter in years"></td>
</tr>
<tr>
<td>Rebates/Incentives</td>
<td></td>
<td></td>
<td><input type="text" name="rebate" placeholder="Please enter in $"></td>
</tr>
<tr>
<td>Interest</td>
<td></td>
<td><input type="text" name="interest1" placeholder="Please enter in %"></td>
<td><input type="text" name="interest2" placeholder="Please enter in %"></td>
</tr>
<tr>
<td>Monthly Payment</td>
<td><input type="text" name="monthly_payment1" placeholder="Please enter in $"></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Distance Limit</td>
<td><input type="text" name="distance_limit" placeholder="Please enter in miles"></td>
</tr>
<tr>
<td>Extra Miles</td>
<td><input type="text" name="extra_miles" placeholder="Please enter in miles"></td>
</tr>
<tr>
<td>Cost for extra mile</td>
<td><input type="text" name="cost_extra" placeholder="Please enter in $"></td>
</tr>
<tr>
<td></td>
<td></td>
<td><br><input type="submit" value="Calculate"></td>
</tr>
</table>
<table id="result">
<tr>
<th></th>
<th>Purchase with finance</th>
<th>Purchase with Rebate</th>
<th>Lease</th>
<th>Purchase after Lease</th>
<th>Purchase after lease with additional miles</th>
</tr>
<tr>
<td>Total Monthly Payments</td>
<td id="mp1"><input type="text"></td>
<td id="mp2"><input type="text"></td>
<td id="mp3"><input type="text"></td>
</tr>
<tr>
<td>Ownership Cost</td>
<td id="oc1"><input type="text"></td>
<td id="oc2"><input type="text"></td>
<td id="oc3"><input type="text"></td>
<td id="oc4"><input type="text"></td>
<td id="oc5"><input type="text"></td>
</tr>
<tr>
<td>Per month owned</td>
<td id="pmo1"><input type="text"></td>
<td id="pmo2"><input type="text"></td>
<td id="pmo3"><input type="text"></td>
<td id="pmo4"><input type="text"></td>
<td id="pmo5"><input type="text"></td>
</tr>
<tr>
<td>Residual Value</td>
<td id="res1"><input type="text"></td>
<td id="res2"><input type="text"></td>
</tr>
<tr> <td></td></tr>
<tr><td></td></tr>
<tr> <td></td></tr>
<tr><td></td></tr>
<tr> <td></td></tr>
<tr><td></td></tr>
</table>
</form>
</div>
</body>
My Javascript is:
function calc()
{
var cost1 = (parseFloat)(document.calc.cost1.value);
var downpayment1 = (parseFloat)(document.calc.downpayment1.value);
var mp1 = (parseFloat)(document.calc.monthly_payment1.value);
var period1 = (parseFloat)(document.calc.period1.value);
var extra_miles = (parseFloat)(document.calc.extra_miles.value);
var cost_extra_miles = (parseFloat)(document.calc.cost_extra_miles.value);
var extra_cost = extra_miles * cost_extra_miles;
var res_amt = 0.56 * cost1;
var totmp = mp1 * period1;
var ocost1 = downpayment1 + totmp + extra_cost;
var omonth1 = ocost1 / period1;
var ocost2 = ocost1 + res_amt;
var omonth2 = ocost2 / period1;
var ocost3 = ocost2 - extra_cost;
var omonth3 = ocost3 / period1;
var cost2 = (parseFloat)(document.calc.cost2.value);
var downpayment2 = (parseFloat)(document.calc.downpayment2.value);
var period2 = (parseFloat)(document.calc.period2.value);
var interest1 = (parseFloat)(document.calc.interest1.value);
var finance1 = cost2 - downpayment2;
var mp2 = ((interest1 / 12) * period2) - finance1;
var omonth_woreb = mp2 * period2;
var ocost_woreb = omonth_woreb + downpayment2;
var pmonth_woreb = ocost_woreb / period2;
var resvalue1 = ocost_woreb - res_amt;
var cost3 = (parseFloat)(document.calc.cost3.value);
var downpayment3 = (parseFloat)(document.calc.downpayment3.value);
var period3 = (parseFloat)(document.calc.period3.value);
var interest2 = (parseFloat)(document.calc.interest2.value);
var rebate = (parseFloat)(document.calc.rebate.value);
var finance2 = cost3 - downpayment3 -rebate;
var mp3 = ((interest1 / 12) * period3) - finance2;
var omonth_wreb = mp3 * period3;
var ocost_wreb = omonth_wreb + downpayment3;
var pmonth_wreb = ocost_wreb / period3;
var resvalue2 = ocost_wreb - res_amt;
document.getElementById("mp1").innerHTML = ;
document.getElementById("mp2").innerHTML = ;
document.getElementById("mp3").innerHTML = totmp;
document.getElementById("oc1").innerHTML = ocost_woreb;
document.getElementById("oc2").innerHTML = ocost_wreb;
document.getElementById("oc3").innerHTML = ocost1;
document.getElementById("oc4").innerHTML = ocost2;
document.getElementById("oc5").innerHTML = ocost3;
document.getElementById("pmo1").innerHTML = pmonth_woreb;
document.getElementById("pmo2").innerHTML = pmonth_wreb;
document.getElementById("pmo3").innerHTML = omonth1;
document.getElementById("pmo4").innerHTML = omonth2;
document.getElementById("pmo5").innerHTML = omonth3;
document.getElementById("res1").innerHTML = resvalue1;
document.getElementById("res2").innerHTML = resvalue2;
}
The following lines aren't syntactically valid:
document.getElementById("mp1").innerHTML = ;
document.getElementById("mp2").innerHTML = ;
If you want to empty the contents of an input, you could use value and an empty string:
document.getElementById("mp1").value = '';
document.getElementById("mp2").value = '';
var cost1 = (parseFloat)(document.calc.cost1.value);
You do not wrap parseFloat in parens.
var cost1 = parseFloat(document.calc.cost1.value);
And you are not cancelling the form submission, the page is refereshing. Easy way to cancel the submission is returning false
onsubmit="calc();return false;"
and this is an error
document.getElementById("mp1").innerHTML = ;
document.getElementById("mp2").innerHTML = ;
Look at this:
The id is on the td, not the input. You are not going to get a value in there if that was your plan.
Related
I am trying to calculate unit total and based on that final total using jQuery, I am able to update unit total every time qty or price is updated, but not able to update final total.
Here is the code:
<table id="tblUpdate" class="dataTable">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Unit Total</th>
</tr>
</thead>
<tbody>
<cfset TotalPrice = 0>
<cfloop query="qItems">
<cfset vLineID = qItems.LineID>
<cfset vUnitTotal = qItems.Quantity * qItems.Price>
<cfset TotalPrice = TotalPrice + vUnitTotal>
<tr data-item-id="#qItems.ItemID#">
<td>#qItems.ItemDescription#</td>
<td><input type="text" name="Quantity_#qItems.LineID#" id="Quantity#vLineID#" class="Quantity" onchange="ChangePrice(#vLineID#,'Quantity');" value="#NumberFormat(qItems.Quantity, '9.99')#" </td>
<td><input type="text" name="Price_#qItems.LineID#" id="UnitPrice#vLineID#" class="Price" onchange="ChangePrice(#vLineID#,'UnitPrice');" value="#NumberFormat(qItems.Price, '9.99')#" </td>
<td id="UnitTotal#vLineID#" class="UnitTotal">#NumberFormat(vUnitTotal,'9.99')#</td>
</tr>
</cfloop>
</tbody>
<tfoot>
<td colspan="4"></td>
<td>Total:</td>
<td id="TotalPrice_Total">#NumberFormat(TotalPrice,'9.99')#</td>
</tfoot>
</table>
And here if the Jquery: The unit total is updating every time when Qty and Price is updated, however, RefreshTotals() function is not updating. Its getting me values but not adding them and calculating final total.
<script>
$(document).ready(function()
{
function ChangePrice(LineID,FieldChanged) {
var Quantity = document.getElementById("Quantity"+LineID);
var UnitPrice = document.getElementById("UnitPrice"+LineID);
var TotalPrice = 0;
var vQuantity = Quantity.value;
var vUnitPrice = UnitPrice.value;
if (FieldChanged == "Quantity" || FieldChanged == "UnitPrice") {
vCustomTotal = vQuantity * vUnitPrice;
$('#UnitTotal' + LineID).text(vCustomTotal.toFixed(2));
}
refreshTotals();
}
function refreshTotals() {
var vTotalPrice = 0;
$('.UnitTotal').each(function(index) {
var r = $("#tblUpdate.UnitTotal").text();
vTotalPrice = vTotalPrice + r;
});
$('#TotalPrice_Total').text(vTotalPrice.toFixed(2));
}
}
</script>
Consider the following example.
$(function() {
function formatCurrency(f) {
return "$" + parseFloat(f).toFixed(2);
}
function refreshTotals() {
var vTotalPrice = 0;
var r;
$(".UnitTotal").each(function(index, element) {
r = parseFloat($(element).text().trim().substring(1));
vTotalPrice += r;
});
$('#TotalPrice_Total').text(formatCurrency(vTotalPrice));
}
function changePrice(Row) {
var Quantity = parseInt($(".Quantity", Row).val());
var UnitPrice = parseFloat($(".Price", Row).val().substring(1));
var TotalPrice = Quantity * UnitPrice;
$(".UnitTotal", Row).html(formatCurrency(TotalPrice));
refreshTotals();
}
$(".Quantity, .Price").change(function() {
changePrice($(this).closest("tr"));
});
refreshTotals();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblUpdate" class="dataTable">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Unit Total</th>
</tr>
</thead>
<tbody>
<tr data-item-id="01">
<td>Item 01</td>
<td><input type="number" min="0" max="999" name="Quantity_01" id="Quantity01" class="Quantity" value="9" /></td>
<td><input type="text" name="Price_01" id="UnitPrice01" class="Price" value="$9.99" /> </td>
<td id="UnitTotal01" class="UnitTotal">$89.91</td>
</tr>
<tr data-item-id="02">
<td>Item 02</td>
<td><input type="number" min="0" max="999" name="Quantity_02" id="Quantity02" class="Quantity" value="6" /></td>
<td><input type="text" name="Price_02" id="UnitPrice02" class="Price" value="$8.88" /> </td>
<td id="UnitTotal01" class="UnitTotal">$53.28</td>
</tr>
<tr data-item-id="03">
<td>Item 03</td>
<td><input type="number" min="0" max="999" name="Quantity_03" id="Quantity03" class="Quantity" value="3" /></td>
<td><input type="text" name="Price_03" id="UnitPrice03" class="Price" value="$7.77" /> </td>
<td id="UnitTotal03" class="UnitTotal">$23.31</td>
</tr>
</tbody>
<tfoot>
<td colspan="2"></td>
<td>Total:</td>
<td id="TotalPrice_Total">$0.00</td>
</tfoot>
</table>
When there are changes to Quantity or Price, the total Unit Price is updated along with the Total. We can pass in the Row and then collect all the details needed from that Row. The value of an input is String so it is best to cast it into the proper Integer or Float as needed. This will ensure that Math operations are correct.
I have a form that looks like this
<form id="calculator" action="#" method="get">
<h1>Cake Cost Estimator</h1>
<h3>Round Cakes:</h3>
<fieldset id="round">
<table>
<tr>
<td><label>6" Round Cake (6-8): </label></td>
<td><input id="6round" type="text" placeholder=0> </td>
</tr>
<tr>
<td><label>8" Round Cake (12-15): </label></td>
<td><input id="8round" type="text" placeholder=0></td>
</tr>
<tr>
<td><label>9" Round Cake (20-24): </label></td>
<td><input id="9round" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>10" Round Cake (26-30): </label></td>
<td><input id="10round" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>12" Round Cake (34-38): </label></td>
<td><input id="12round" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>14" Round Cake (46-50): </label></td>
<td><input id="14round" type="text" placeholder=0 ></td>
</tr>
</table>
</fieldset>
<h3>Square Cakes:</h3>
<fieldset id="square">
<table>
<tr>
<td><label>6" Square Cake (8-10): </label></td>
<td><input id="6square" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>8" Square Cake (14-18): </label></td>
<td><input id="8square" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>9" Square Cake (22-26): </label></td>
<td><input id="9square" type="text" placeholder=0 ></td>
<tr>
<td><label>10" Square Cake (28-32): </label></td>
<td><input id="10square" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>12" Square Cake (38-40): </label></td>
<td><input id="12square" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>14" Square Cake (56-60): </label></td>
<td><input id="14square" type="text" placeholder=0></td>
</table>
</fieldset>
<h3>Sheet Cake:</h3>
<fieldset id="sheet">
<table>
<tr>
<td><label>1/4 Sheet (15-18): </label></td>
<td><input id="quarter" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>1/2 Sheet (30-35): </label></td>
<td><input id="half" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>Full Sheet (65-70): </label></td>
<td><input id="full" type="text" placeholder=0 ></td>
</tr>
</table>
</fieldset>
<h3>Cupcakes:</h3>
<fieldset id="cupcakes">
<table>
<tr>
<td><label>Basic Cupcake: </label></td>
<td><input id="basic" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>Standard Cupcake: </label></td>
<td><input id="standard" type="text" placeholder=0 ></td>
</tr>
<tr>
<td><label>Premium: </label></td>
<td><input id="premium" type="text" placeholder=0 ></td>
</tr>
</table>
</fieldset>
<h3>TOTAL: $ <input id="total" type="text" placeholder=0 disabled="disabled"></h3>
The javascript looks like this
//Prices
$(document).ready(function(){
//apparently you can't declare a variable with a number and letter
var sixround = 39.95;
var eightround = 45.95;
var nineround = 52.95;
var tenround = 60.95;
var twelveround = 74.95;
var fourteenround = 89.95;
var sixsquare = 45.95;
var eightsquare = 52.95;
var ninesquare = 60.95;
var tensquare = 74.95;
var twelvesquare = 99.95;
var fourteensquare = 116.95;
var quarterSheet = 37.95;
var halfSheet = 62.94;
var fullSheet = 95.95;
var basicCupcake = 2.25;
var standardCupcake = 2.50;
var premiumCupcake = 2.75;
//Round cakes
$("#6round").keyup(function() {
//get the value of the key you just entered
var six =$("#6round").val();
//multiply the value by the amount
$("#total").val((sixround *six).toFixed(2));
});
$("#8round").keyup(function() {
var eight =$("#8round").val();
$("#total").val((eightround * eight).toFixed(2));
});
$("#9round").keyup(function() {
var nine =$("#9round").val();
$("#total").val((nineround * nine).toFixed(2));
});
$("#10round").keyup(function() {
var ten = $("#10round").val();
$("#total").val((tenround * ten).toFixed(2));
});
$("#12round").keyup(function() {
var twelve = $("#12round").val();
$("#total").val((twelveround *twelve).toFixed(2));
});
$("#14round").keyup(function() {
var fourteen = $("#14round").val();
$("#total").val((fourteenround * fourteen).toFixed(2));
});
//Square Cakes
$("#6square").keyup(function() {
var sixs = $("#6square").val();
$("#total").val((sixsquare * sixs).toFixed(2));
});
$("#8square").keyup(function() {
var eights = $("#8square").val();
$("#total").val((eightsquare * eights).toFixed(2));
});
$("#9square").keyup(function() {
var nines = $("#9square").val();
$("#total").val((ninesquare * nines).toFixed(2));
});
$("#10square").keyup(function() {
var tens = $("#10square").val();
$("#total").val((tensquare * tens).toFixed(2));
});
$("#12square").keyup(function() {
var twelves = $("#12square").val();
$("#total").val((twelvesquare * twelves).toFixed(2));
});
$("#14square").keyup(function() {
var fourteens = $("#14square").val();
$("#total").val((fourteensquare * fourteens).toFixed(2));
});
//renamed the elemet ids in the html to quarter half and full becuase it didn't like the numbers
//Sheet Cakes
$("#quarter").keyup(function() {
var quart = $("#quarter").val();
$("#total").val((quarterSheet * quart).toFixed(2));
});
$("#half").keyup(function() {
var halfs = $("#half").val();
$("#total").val((halfSheet * halfs).toFixed(2));
});
$("#full").keyup(function() {
var fulls = $("#full").val();
$("#total").val((fullSheet * fulls).toFixed(2));
});
//Cupcakes
$("#basic").keyup(function() {
var bas = $("#basic").val();
$("#total").val((basicCupcake * bas).toFixed(2));
});
$("#standard").keyup(function() {
var stand = $("#standard").val();
$("#total").val((standardCupcake * stand).toFixed(2));
});
$("#premium").keyup(function() {
var prem = $("#premium").val();
$("#total").val((premiumCupcake * prem).toFixed(2));
});
});
This calculates the cost or total of the whole thing for each individual form id like a 6 round cake then can enter a number and it calculates the price for that particuar one. But how do I keep a running total of the total cost
I think differently. I solve this problem with html element attribute.
With this way you can add a lot of input boxes to your page. But you must not forget two attribute class="amountBox" data-var="(this is price which you added to priceList object before)"
then javascript calculates total value. Here jsfiddle : http://jsfiddle.net/5wbhnmwd/
By this way you get rid of the js manipulation for each element that you add to document.
<form id="calculator" action="#" method="get">
<h1>Cake Cost Estimator</h1>
<h3>Round Cakes:</h3>
<fieldset id="round">
<table>
<tr>
<td>
<label>6" Round Cake (6-8):</label>
</td>
<td>
<input id="6round" class="amountBox" data-var="sixround" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>8" Round Cake (12-15):</label>
</td>
<td>
<input id="8round" class="amountBox" data-var="eightround" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>9" Round Cake (20-24):</label>
</td>
<td>
<input id="9round" class="amountBox" data-var="nineround" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>10" Round Cake (26-30):</label>
</td>
<td>
<input id="10round" class="amountBox" data-var="tenround" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>12" Round Cake (34-38):</label>
</td>
<td>
<input id="12round" class="amountBox" data-var="twelveround" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>14" Round Cake (46-50):</label>
</td>
<td>
<input id="14round" class="amountBox" data-var="fourteenround" type="text" placeholder=0>
</td>
</tr>
</table>
</fieldset>
<h3>Square Cakes:</h3>
<fieldset id="square">
<table>
<tr>
<td>
<label>6" Square Cake (8-10):</label>
</td>
<td>
<input id="6square" class="amountBox" data-var="sixsquare" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>8" Square Cake (14-18):</label>
</td>
<td>
<input id="8square" class="amountBox" data-var="eightsquare" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>9" Square Cake (22-26):</label>
</td>
<td>
<input id="9square" class="amountBox" data-var="ninesquare" type="text" placeholder=0>
</td>
<tr>
<td>
<label>10" Square Cake (28-32):</label>
</td>
<td>
<input id="10square" class="amountBox" data-var="tensquare" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>12" Square Cake (38-40):</label>
</td>
<td>
<input id="12square" class="amountBox" data-var="twelvesquare" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>14" Square Cake (56-60):</label>
</td>
<td>
<input id="14square" class="amountBox" data-var="fourteensquare" type="text" placeholder=0>
</td>
</table>
</fieldset>
<h3>Sheet Cake:</h3>
<fieldset id="sheet">
<table>
<tr>
<td>
<label>1/4 Sheet (15-18):</label>
</td>
<td>
<input id="quarter" class="amountBox" data-var="quarterSheet" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>1/2 Sheet (30-35):</label>
</td>
<td>
<input id="half" class="amountBox" data-var="halfSheet" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>Full Sheet (65-70):</label>
</td>
<td>
<input id="full" class="amountBox" data-var="fullSheet" type="text" placeholder=0>
</td>
</tr>
</table>
</fieldset>
<h3>Cupcakes:</h3>
<fieldset id="cupcakes">
<table>
<tr>
<td>
<label>Basic Cupcake:</label>
</td>
<td>
<input id="basic" class="amountBox" data-var="basicCupcake" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>Standard Cupcake:</label>
</td>
<td>
<input id="standard" class="amountBox" data-var="standardCupcake" type="text" placeholder=0>
</td>
</tr>
<tr>
<td>
<label>Premium:</label>
</td>
<td>
<input id="premium" class="amountBox" data-var="premiumCupcake" type="text" placeholder=0>
</td>
</tr>
</table>
</fieldset>
<h3>TOTAL: $ <input id="total" type="text" placeholder=0 disabled="disabled"></h3>
//Prices
$(document).ready(function () {
var priceList = {
sixround : 39.95,
eightround : 45.95,
nineround : 52.95,
tenround : 60.95,
twelveround : 74.95,
fourteenround : 89.95,
sixsquare : 45.95,
eightsquare : 52.95,
ninesquare : 60.95,
tensquare : 74.95,
twelvesquare : 99.95,
fourteensquare : 116.95,
quarterSheet : 37.95,
halfSheet : 62.94,
fullSheet : 95.95,
basicCupcake : 2.25,
standardCupcake : 2.50,
premiumCupcake : 2.75
};
$('.amountBox').on('change', function(){
var value = $(this).val();
var price = priceList[$(this).data('var')];
$(this).val((value*price).toFixed(2));
$('#total').val('0');
$('.amountBox').each(function(){
if(!isNaN(parseFloat($(this).val()))){
$('#total').val((parseFloat($('#total').val()) + parseFloat($(this).val())).toFixed(2));
}
});
});
});
When you are calculating the new value, just do something like:
$("#8square").keyup(function() {
var eights = $("#8square").val();
var oldValue = $("#total").val();
$("#total").val(parseInt(oldValue) + parseInt((eightsquare * eights).toFixed(2)));
});
However, this assumes they enter in all the correct values the first time. Have some way to subtract from the total should they remove their choice and make a new one.
Check the following demo: http://jsbin.com/yobeyonuju/1/
function getRes(){
total = document.getElementById('total');
total.value=0;
f = document.getElementById('calculator');
inputs = f.getElementsByTagName('input');
res = 0;
for (i = 0; i < inputs.length; i++){
if (!isNaN(inputs[i].value*1)) res += inputs[i].value*1;
}
total.value = res;
}
It is clear that isNaN for exclude any inputs such as submit without numerical values. In the demo I called it from javascript hyper link as
TOTAL:
You're updating the value of #total with only the value of the form field that's being changed... you need to give all of your form fields a class and then add the sum of all fields every time one of them changes. It's also better to use change instead of keyup so you get the total only when the input is changed and out of focus.
$(".subtotal").change(function () {
$("#total").val(0);
var sum = 0;
$('.subtotal').each(function () {
sum += Number($(this).val());
});
$("#total").val(sum.toFixed(2));
});
JSFiddle
I have a small question and I hope someone can help me with it :D
I’m trying to create a product table, in which a user just add the quantity of a product and the jquery makes the multiplication to its value and gives the result
I already made this, and it works well:
<script>
$(document).ready(function(){
$('#quantity_1').keyup(function(){
var price_1 = $("#price_1").val();
var quantity_1 = $("#quantity_1").val();
quantity_1 = quantity_1.replace(/[^0-9]+/g, '');
$("#quantity_1").val(quantity_1);
var total_1 = price_1 * quantity_1;
$( "#total_1" ).val( total_1.toFixed(2) );
});
});
</script>
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
</table>
Working demo here:
http://jsfiddle.net/EnterateNorte/9kswL0gf/
But I would like to be able to add more than one line, like so:
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Name 1</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
<tr>
<td>Name 5</td>
<td><input type="hidden" name="product[5][price]" id="price_5" value="10.00" />23.00</td>
<td><input type="text" name="product[5][quantity]" id="quantity_5" /></td>
<td><input type="text" name="product[5][total]" id="total_5" value="0" /></td>
</tr>
<tr>
<td>Name 3</td>
<td><input type="hidden" name="product[3][price]" id="price_3" value="130.00" />10.00</td>
<td><input type="text" name="product[3][quantity]" id="quantity_3" /></td>
<td><input type="text" name="product[3][total]" id="total_3" value="0" /></td>
</tr>
<tr>
<td>Name 4</td>
<td><input type="hidden" name="product[4][price]" id="price_4" value="12.00" />10.00</td>
<td><input type="text" name="product[4][quantity]" id="quantity_4" /></td>
<td><input type="text" name="product[4][total]" id="total_4" value="0" /></td>
</tr>
</table>
And if it isn’t to much trouble, I would be awesome if it would SUM all the totals and show a gran total at the end of the table :)
Use:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var price = $(this).parent().prev().find('input').val();
var quantity = $(this).val();
var total = price * quantity;
$(this).parent().next().find('input').val( total.toFixed(2) );
});});
Working Demo
Update: For showing Grand Total
var sum = 0;
//iterate through each textboxes and add the values
$('[name*=total]').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseInt(this.value);
}
});
Working Demo
What you can do is to find the elements using their relative position instead of hard coded ids
$(document).ready(function () {
$('input[id^="quantity_"]').keyup(function () {
var $tr = $(this).closest('tr');
var price = $tr.find('input[id^="price_"]').val();
var quantity = this.value;
var total = (price * quantity) || 0;
$tr.find('input[id^="total_"]').val(total.toFixed(2));
});
});
Demo: Fiddle
I've updated your code in Fiddle. You need to change in your markup a bit.
<tr>
<td>Product Name</td>
<td><input type="hidden" class="price" ... />10</td>
<td><input type="text" class="quantity" ... /></td>
<td><input type="text" class="total" ... /></td>
</tr>
$(document).ready(function(){
$('.quantity').keyup(function(){
var parent = $(this).closest("tr");
var price = $(".price", parent).val();
var quantity = $(".quantity", parent).val();
var total = price * quantity;
$(".total", parent).val(total.toFixed(2));
});
});
I would recommend you to use common class
HTML:
<tr>
<td>Name 5</td>
<td>
<input type="hidden" class="price" value="10.00" />10.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
<tr>
<td>Name 3</td>
<td>
<input type="hidden" class="price" value="130.00" />130.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
Script:
$('.quantity').keyup(function () {
var tr = $(this).closest('tr');
var price = tr.find('.price').val();
var quantity = $(this).val();
var total = price * quantity;
tr.find('.total').val(total.toFixed(2));
});
DEMO
Modify your table:
<table border="1" cellpadding="5px" cellspacing="0" id='table' >
<!-- your rows with inputs -->
<tr>
<td>
<input id='totalSum' value='0' type='text' />
</td>
</tr>
</table>
Make all your 'total' inputs readonly by adding 'readonly' attribute.
js code:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var total = 0;
$('#table tr').each(function(i,item){
var price = parseFloat($(item).find('[name*=price]').val().replace(',','.'));
var quantity = parseInt($(item).find('[name*=quantity]').val());
if(!isNaN(price) && !isNan(quantity)){
total += price*quantity;
}
});
$("#totalSum").val(total.toFixed(2));
});
});
I'm very new to JavaScript and I have an assignment that I'm unable to resolve. So I have a table with five fields and I need to calculate the total for a month, then automatically generate the yearly total in a different cell. I got to make the total work for the month but I have no idea how to reflect that in the year cells. Any help will be much appreciated. Thanks a lot for your time :)
Here's my code:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function update() {
var a = +document.forms['calc'].elements['fieldOne'].value,
b = +document.forms['calc'].elements['fieldTwo'].value,
c = +document.forms['calc'].elements['fieldThree'].value,
d = +document.forms['calc'].elements['fieldFour'].value,
e = +document.forms['calc'].elements['fieldFive'].value,
fieldTotal = ((b-d)*a)*c;
document.forms['calc'].elements['fieldTotal'].value = fieldTotal;
return false;
}
function update2() {
var f = +document.forms['calc'].elements['field6'].value,
g = +document.forms['calc'].elements['field7'].value,
h = +document.forms['calc'].elements['field8'].value,
i = +document.forms['calc'].elements['fieldFour'].value,
j = +document.forms['calc'].elements['fieldFive*12'].value,
field9=fieldFour;
field10=fieldFive*12;
fieldTotal2=fieldTotal*12;
document.write('fieldTotal2');
document.write('field9');
document.write('field10');
return false;
}
</script>
</head>
<body>
<form name="calc" action="#">
<table width="600" border="1">
<tr>
<td colspan="2"> </td>
<td width="63">Month</td>
<td width="109">Year</td>
</tr>
<tr>
<td colspan="2">Field1</td>
<td><input type="text" name="fieldOne" id="fieldOne" size="15" value="5,000" /></td>
<td><input type="text" name="field6" id="field6" size="15" value="60,000"/></td>
</tr>
<tr>
<td colspan="2">Field2</td>
<td><input type="text" name="fieldTwo" id="fieldTwo" value="3.0" size="15" /></td>
<td><input type="text" name="field7" id="field7" value="3.0" size="15" /></td>
</tr>
<tr>
<td colspan="2">Field3</td>
<td><input type="text" name="fieldThree" id="fieldThree" size="15" value="$350"/></td>
<td><input type="text" name="field8" id="field8" size="15" value="$350"/></td>
</tr>
<tr>
<td colspan="2">Field4</td>
<td><input type="text" name="fieldFour" id="fieldFour" value="1.5" size="15" /></td>
<td><input type="number" name="field9" id="field9" value="1.5" size="15" /></td>
</tr>
<tr>
<td colspan="2">Filed5</td>
<td><input type="text" name="fieldFive" id="fieldFive" size="15" value="75"/></td>
<td><input type="text" name="field10" id="field10" size="15" /></td>
</tr>
<tr>
<td width="137">Total</td>
<td width="83"><input type="button" value="Calculate" onClick="update();return false;" /></td>
<td><input type="text" name="fieldTotal" id="fieldTotal" size="15" readonly /></td>
<td><input type="text" name="fieldTotal2" id="fieldTotal2" size="15" readonly /></td>
</tr>
</table>
</form>
</body>
Based on what you described I think this should work for you.
Demo
function update() {
var frmEles = document.forms.calc.elements,
a = frmEles.fieldOne.value.replace(',',''), //Remove comma
b = frmEles.fieldTwo.value,
c = frmEles.fieldThree.value.replace('$',''), //Remove Dollar sign
d = frmEles.fieldFour.value,
e = frmEles.fieldFive.value,
fieldTotal = ((b-d)*a)*c;
//Total for the month
frmEles.fieldTotal.value = formatNumber(fieldTotal);
//Calculations for the year
frmEles.field6.value = formatNumber(a * 12);
frmEles.field7.value = formatNumber(b * 12);
frmEles.field8.value = '$' + formatNumber(c * 12); //Add back dollar sign
frmEles.field9.value = formatNumber(d * 12);
frmEles.field10.value = formatNumber(e * 12);
frmEles.fieldTotal2.value = formatNumber(fieldTotal * 12);
return false;
}
//Format the numbers with commas.
function formatNumber(n){
return n.toLocaleString();
}
I am trying to calculate the "sub_total" field based on:
"total_full" + "total_half". however the javascript which i tried is not working. the result of sub_total is displaying as "0".
How can I improve my javascript "calculate sub total" to allow me to add "total_full" and "total_half" together? ( I will then also implement the sub_total calculation to include "total_single", "total_double", and "total_projector" as well when I can get the calculation right.
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Conference Form</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jqueryui.js"></script>
<link href="style.css" rel="stylesheet" type="text/css"/>
<link href="css/jqueryui.css" rel="stylesheet" type="text/css" />
<body>
<div id="wrapper">
<div id="header"></div>
<table width="899" border="1" align="left" cellpadding="1">
<form action="" method="get" name="myform">
<tr>
<td width="258"><label>Company Name</label></td>
<td width="249"><input type="text" name="companyname" id="companyname" /></td>
<td width="27"> </td>
<td width="186">Enquiry Date</td>
<td width="145"><input type="text" name="enquiry_date" id="enquiry_date" class="datepicker" /></td>
</tr>
<tr>
<td>Conference Date In</td>
<td><input type="text" name="conference_date_in" id="conference_date_in" class="datepicker" /></td>
<td> </td>
<td>Conference Date Out</td>
<td><input type="text" name="conference_date_out" id="conference_date_out" class="datepicker" /></td>
</tr>
<tr>
<td>Total Days</td>
<td><input type="text" name="total_days" id="total_days" /></td>
</tr>
<tr>
<td>Number of Delegates</td>
<td><input type="text" name="no_of_delegates" id="no_of_delegates" /></td>
</tr>
<tr>
<td>Accommodation:</td>
<tr>
<td><p>Check in Date</p></td>
<td><input type="text" name="check_in_date" id="check_in_date" class="datepicker" /></td>
<td><p>Check out Date</p></td>
<td><p>
<input type="text" name="check_out_date" id="check_out_date" class="datepicker" />
</p></td>
</tr>
<tr>
<td>Total Days Accommodation</td>
<td><input type="text" name="total_days_acc" id="total_days_acc" /></td>
</tr>
<tr>
<td><strong>Contact Details</strong></td>
</tr>
<tr>
<td>Contact Person</td>
<td><input type="text" name="contact_person" id="contact_person" /></td>
</tr>
<tr>
<td>Telephone Number</td>
<td><input type="text" name="tel_no" id="tel_no" /></td>
<td> </td>
<td>Fax Number</td>
<td><input type="text" name="fax_no" id="fax_no" /></td>
</tr>
<tr>
<td>Cell Number</td>
<td><input type="text" name="cell_no" id="cell_no" /></td>
<td> </td>
<td>Email</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Full Day Conference # R260 p/p</td>
<td><input type="text" name="full_day" id="full_day" />
Full Days</td>
<td> </td>
<td>Total Cost Full Day</td>
<td><input type="text" name="total_full" id="total_full" readonly="readonly" /></td>
</tr>
<tr>
<td>Half Day Conference # R240 p/p</td>
<td><input type="text" name="half_day" id="half_day" />
Half Days</td>
<td> </td>
<td>Total Cost Half Day</td>
<td><input type="text" name="total_half" id="total_half" readonly="readonly" /></td>
</tr>
<tr>
<td>Single Rooms # R480 p/p</td>
<td><input type="text" name="single_rooms" id="single_rooms" />
Guests</td>
<td> </td>
<td>Total Cost Single Rooms</td>
<td><input name="total_single" type="text" id="total_single" readonly="readonly" /></td>
</tr>
<tr>
<td>Double / Twin Rooms # R360 p/p/s</td>
<td><input type="text" name="double_rooms" id="double_rooms" />
Guests</td>
<td> </td>
<td>Total Cost Double / Twin</td>
<td><input name="total_double" type="text" id="total_double" readonly="readonly" /></td>
</tr>
<tr>
<td>Data Projector # R400 rental p/day</td>
<td><input type="text" name="data_projector" id="data_projector" />
Days</td>
<td> </td>
<td>Total Cost Projector Rental</td>
<td><input name="total_projector" type="text" id="total_projector" readonly="readonly" /></td>
</tr>
<tr>
<td>Sub Total</td>
<td><input name="sub_total" type="text" id="sub_total" readonly="readonly" /></td>
</tr>
<tr>
<td height="23"> </td>
</tr>
</form>
</table>
</div>
<div id="hideme">
Hello Hideme
</div>
</body>
</html>
JAVASCRIPT
<script type="text/javascript">
//Datepicker
$(function() {
$(".datepicker").datepicker({ minDate: -0, maxDate: "+100M +10D",dateFormat: 'dd-mm-yy'})
({
changeMonth: true,
changeYear: true,
});
});
//Datepicker Enquiry Date Set to Today
var enquiry_date = $.datepicker.formatDate('dd-mm-yy', new Date());
document.getElementById('enquiry_date').value = enquiry_date;
//Datepicker Conference in / out
var calcDate = function() {
var start = $('#conference_date_in').datepicker('getDate');
var end = $('#conference_date_out').datepicker('getDate');
var days = (end - start) / 1000 / 60 / 60 / 24 + 1;
if(days==0) {days=1
}
if( days >= 0 ) {
document.getElementById('total_days').value = days;
}
}
$('#conference_date_out').change(calcDate);
$('#conference_date_in').change(calcDate);
//Datepicker Check in / Out Accommodation
var calcDateAcc = function() {
var startacc = $('#check_in_date').datepicker('getDate');
var endacc = $('#check_out_date').datepicker('getDate');
var daysacc = (endacc - startacc) / 1000 / 60 / 60 / 24;
if(daysacc==0) daysacc=1
if( daysacc >= 0 ) {
document.getElementById('total_days_acc').value = daysacc;
}
}
$('#check_in_date').change(calcDateAcc);
$('#check_out_date').change(calcDateAcc);
//Calculate Total Cost FullDay Conference
function calculateFull()
{
var fulldays = parseInt(document.getElementById("full_day").value);
var no_of_delegates = parseInt(document.getElementById("no_of_delegates").value);
var fullprice = 260;
var resultfull = fulldays * no_of_delegates * fullprice;
document.getElementById("total_full").value = resultfull;
}
$('#full_day').change(calculateFull).keyup(calculateFull);
//Calculate Half Day conference total
function calculateHalf()
{
var halfdays = parseInt(document.getElementById("half_day").value);
var no_of_delegates = parseInt(document.getElementById("no_of_delegates").value);
var halfprice = 240;
var resulthalf = halfdays * no_of_delegates * halfprice;
document.getElementById("total_half").value = resulthalf;
}
$('#half_day').change(calculateHalf).keyup(calculateHalf);
//Calculate Total Cost Single Rooms
function calculateSingle()
{
var single_rooms = parseInt(document.getElementById("single_rooms").value);
var total_days_acc = parseInt(document.getElementById("total_days_acc").value);
var single_rooms_price = 480;
var resultsingle = single_rooms * total_days_acc * single_rooms_price;
document.getElementById("total_single").value = isNaN(resultsingle) ? 0 : resultsingle;
}
$('#single_rooms').change(calculateSingle).keyup(calculateSingle);
$('#check_in_date').change(calculateSingle);
$('#check_out_date').change(calculateSingle);
//Calculate Total Cost Double / Twin Rooms
function calculateDouble()
{
var double_rooms = parseInt(document.getElementById("double_rooms").value);
var total_days_acc = parseInt(document.getElementById("total_days_acc").value);
var double_rooms_price = 360;
var resultdouble = double_rooms * total_days_acc * double_rooms_price;
document.getElementById("total_double").value = isNaN(resultdouble) ? 0 : resultdouble;
}
$('#double_rooms').change(calculateDouble).keyup(calculateDouble);
$('#check_in_date').change(calculateDouble);
$('#check_out_date').change(calculateDouble);
//Calculate Total Cost Date Projector
function calculateProjector()
{
var data_projector = parseInt(document.getElementById("data_projector").value);
var data_projector_price = 400;
var resultdata = data_projector * data_projector_price;
document.getElementById("total_projector").value = isNaN(resultdata) ? 0 : resultdata;
}
$('#data_projector').change(calculateProjector).keyup(calculateProjector);
//Calculate Sub Total
function calculateSubTotal()
{
var SubTotal = total_full + total_half;
document.getElementById("sub_total").value = isNaN(SubTotal) ? 0 : SubTotal;
}
$('#data_projector').change(calculateSubTotal).keyup(calculateSubTotal);
//Hide me Testing
$("#full_day").keyup(function(){
if ($('#full_day').val() == "1") {
$("#hideme").show("fast"); //Slide Down Effect
}
else {
$("#hideme").hide("fast"); //Slide Up Effect
}
});
</script>
Does this do what you want :
//Calculate Sub Total
function calculateSubTotal()
{
var SubTotal = +total_full.value + +total_half.value;
document.getElementById("sub_total").value = isNaN(SubTotal) ? 0 : SubTotal;
}
document.getElementById("total_half").onchange = calculateSubTotal;
document.getElementById("total_half").onkeyup = calculateSubTotal;
Note the use of unary + and .value when getting the values entered in total_full and total_half. Also the setting the of event handlers.
Try it out here : http://jsfiddle.net/jstoolsmith/ue62p/