This question already has answers here:
Gaussian/banker's rounding in JavaScript
(9 answers)
Closed 3 years ago.
<script >
function sum() {
var txtFirstNumberValue = document.getElementById('studentenrolled').value;
var txtSecondNumberValue = document.getElementById('classsize').value;
var result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('nooftut').value = result;
}
}
</script>
<tr>
<td><label for="studentenrolled">Student Enrolled</label> </td>
<td> <input type="text" name="studentenrolled" id="studentenrolled" value="<?php echo $row['studentenrolled']; ?> " /></td>
</tr>
<tr>
<td><label for="classsize">Class Size</label> </td>
<td> <input type="text" id="classsize" onkeyup="sum();" /></td>
</tr>
<tr>
<td><label for="nooftut">No Of Tutorial</label> </td>
<td> <input type="text" id="nooftut" disabled="disabled" /></td>
</tr>
How to I round up or down the results in "nooftut"
Calculation : studentenrolled / class size = nooftut
As studentenrolled is pulled from the db, I'm not able to round up or down
Try Math.round()
function sum() {
var txtFirstNumberValue = document.getElementById('studentenrolled').value;
var txtSecondNumberValue = document.getElementById('classsize').value;
var result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('nooftut').value = Math.round(result);
}
}
<tr>
<td><label for="studentenrolled">Student Enrolled</label> </td>
<td> <input type="text" name="studentenrolled" id="studentenrolled" value=" " /></td>
</tr>
<tr>
<td><label for="classsize">Class Size</label> </td>
<td> <input type="text" id="classsize" onkeyup="sum();" /></td>
</tr>
<tr>
<td><label for="nooftut">No Of Tutorial</label> </td>
<td> <input type="text" id="nooftut" disabled="disabled" /></td>
</tr>
+1.5 => +1.0 using Math.floor() (To round down)
-1.5 => -1.0 using Math.ceil() (To round up)
or just Math.round(0.9) => 1
Related
When I just put in a quantity everything works as it should and rounds the .values to 2 decimal places but when I select a option in my drop down selector for lets says 6 Piece $7.99 it no longer displays the .value as 2 decimal places. Can anyone help me make my values for Tax and Total display 2 decimal places when a option is selected for a wing count?
I've already tried to add .toFixed(2) to the total and tax.value in my update() function in my script.
<table>
<tr style="background-color:black; color:white" >
<th>Menu Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Preferance</th>
</tr>
<tr>
<td>Boneless Chicken Wings</td>
<td><input type="text" value="" name="QTY" id="QTY" onKeyUp="multiply()" /></td>
<td><input type="text" name="PPRICE" id="PPRICE" value="5.99" disabled="disabled" readonly/></td>
</td>
<td>
<form action="/action_page.php">
<select id="BONELESS_COUNT" onkeyup="update()" onchange="update()">
<option value="0.00" name="4PCBL" id="4PCBL">4 Piece $5.99</option>
<option value="2.00" name="6PCBL" id="6PCBL">6 Piece $7.99</option>
<option value="4.00" name="12PCBL" id="12PCBL">12 Piece $9.99</option>
</select>
<select name="Preparation">
<option value="Baked">Baked</option>
<option value="Fried">Fried</option>
</select>
<select name="Flavor">
<option>Original</option>
<option>Buffalo</option>
<option>Parmesian</option>
<option>Lemon Pepper</option>
<option>BBQ</option>
</select>
</form>
</td>
</tr>
<tr>
<td></td>
<td><input type="text" name="4PCBLM" id="4PCBLM" value="1" disabled="disabled" style="display:none"readonly/></td>
<td><input type="text" name="6PCBLM" id="6PCBLM" value="1" disabled="disabled" style="display:none"readonly/></td>
<td><input type="text" name="12PCBLM" id="12PCBLM" value="1" disabled="disabled" style="display:none"readonly/></td>
<td><input type="text" name="TAXDIV" id="TAXDIV" value="100" disabled="disabled" style="display:none"readonly/></td>
</tr>
<tr>
<td></td>
<td align="right"><strong>Subtotal $</strong></td>
<td><input type="text" name="SUBTOTAL" id="SUBTOTAL"></td>
<td></td>
</tr>
<tr>
<td></td>
<td align="right" style="display:none"><strong>Salestax</strong></td>
<td><input type="text"name="SALESTAX" id="SALESTAX" value="11" disabled="disabled" style="display:none" readonly/></td>
<td></td>
</tr>
<tr>
<td></td>
<td align="right"><strong>Tax $</strong></td>
<td><input type="text" name="TAX" id="TAX" /></td>
<td></td>
</tr>
<td></td>
<td></td>
<tr>
<td></td>
<td align="right"><strong>Total $</strong></td>
<td><input type="text" name="TOTAL" id="TOTAL"></td>
<td></td>
</tr>
function multiply() {
a = Number(document.getElementById('QTY').value);
b = Number(document.getElementById('PPRICE').value);
c = Number(document.getElementById('4PCBL').value);
d = Number(document.getElementById('4PCBLM').value);
e = Number(document.getElementById('6PCBL').value);
f = Number(document.getElementById('6PCBLM').value);
g = Number(document.getElementById('12PCBL').value);
h = Number(document.getElementById('12PCBLM').value);
i = a * b;
j = Number(document.getElementById('SALESTAX').value);
k = i * j;
l = Number(document.getElementById('TAXDIV').value);
m = k / l;
n = i + m;
document.getElementById('SUBTOTAL').value = i.toFixed(2);
document.getElementById('TAX').value = m.toFixed(2);
document.getElementById('TOTAL').value = n.toFixed(2);
}
function update() {
var pprice = document.getElementById("PPRICE")
var subtotal = document.getElementById("SUBTOTAL")
var tax = document.getElementById("TAX")
var total = document.getElementById("TOTAL")
qty = document.getElementById("QTY")
choice = document.getElementById("BONELESS_COUNT")
pprice.value = b + (choice.options[choice.selectedIndex].value * QTY.value)
subtotal.value = i + (choice.options[choice.selectedIndex].value * QTY.value)
tax.value = (subtotal.value * j) / l
total.value = (b + (choice.options[choice.selectedIndex].value * QTY.value)) * j / l + (b + (choice.options[choice.selectedIndex].value * QTY.value))
}
It looks like you forgot to also use .toFixed(2) in your update function, i.e.
tax.value = ((subtotal.value * j) / l).toFixed(2)
total.value = ((b + (choice.options[choice.selectedIndex].value * QTY.value)) * j / l + (b + (choice.options[choice.selectedIndex].value * QTY.value))).toFixed(2)
You could greatly simplify your code down to just this. Notice that giving variables proper names rather than "a, b, c.." makes things much easier to understand and will help you a lot when you're trying to figure out why things aren't working.
Also, you really want to declare variables with let (if the value may change later), or const (if the value will never change). Note that each time update() gets called, the const variables there get recreated since they are scoped inside of the function. The values they hold never get changed within the function, so they can be const.
Without using let or const you are creating global variables which will cause you a lot of problems.
// I am prepending $ to variable names to remind me that these are HTML elements
const $qty = document.getElementById("QTY");
const $choice = document.getElementById("BONELESS_COUNT");
const $subtotal = document.getElementById("SUBTOTAL");
const $pprice = document.getElementById("PPRICE");
const $tax = document.getElementById("TAX");
const $total = document.getElementById("TOTAL");
const salesTaxRate = Number(document.getElementById("SALESTAX").value) / 100;
function update() {
const qty = Number($qty.value);
const meal_price = Number($choice.options[$choice.selectedIndex].value);
const subtotal = qty * meal_price;
const tax = subtotal * salesTaxRate;
const total = subtotal + tax;
$subtotal.value = subtotal.toFixed(2);
$pprice.value = subtotal.toFixed(2);
$tax.value = tax.toFixed(2);
$total.value = total.toFixed(2);
}
<table>
<tr style="background-color:black; color:white">
<th>Menu Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Preference</th>
</tr>
<tr>
<td>Boneless Chicken Wings</td>
<td><input type="text" value="" name="QTY" id="QTY" onKeyUp="update()" /></td>
<td><input type="text" name="PPRICE" id="PPRICE" value="" disabled="disabled" readonly/></td>
</td>
<td>
<form action="/action_page.php">
<select id="BONELESS_COUNT" onkeyup="update()" onchange="update()">
<option value="5.99" name="4PCBL" id="4PCBL">4 Piece $5.99</option>
<option value="7.99" name="6PCBL" id="6PCBL">6 Piece $7.99</option>
<option value="9.99" name="12PCBL" id="12PCBL">12 Piece $9.99</option>
</select>
<select name="Preparation">
<option value="Baked">Baked</option>
<option value="Fried">Fried</option>
</select>
<select name="Flavor">
<option>Original</option>
<option>Buffalo</option>
<option>Parmesian</option>
<option>Lemon Pepper</option>
<option>BBQ</option>
</select>
</form>
</td>
</tr>
<tr>
<!-- not sure what this is for? -->
<td></td>
<td><input type="text" name="4PCBLM" id="4PCBLM" value="1" disabled="disabled" style="display:none" readonly/></td>
<td><input type="text" name="6PCBLM" id="6PCBLM" value="1" disabled="disabled" style="display:none" readonly/></td>
<td><input type="text" name="12PCBLM" id="12PCBLM" value="1" disabled="disabled" style="display:none" readonly/></td>
</tr>
<tr>
<td></td>
<td align="right"><strong>Subtotal $</strong></td>
<td><input type="text" name="SUBTOTAL" id="SUBTOTAL"></td>
<td></td>
</tr>
<tr>
<td></td>
<td align="right" style="display:none"><strong>Salestax</strong></td>
<!-- you could just put this directly in your code -->
<td><input type="text" name="SALESTAX" id="SALESTAX" value="11" disabled="disabled" style="display:none" readonly/></td>
<td></td>
</tr>
<tr>
<td></td>
<td align="right"><strong>Tax $</strong></td>
<td><input type="text" name="TAX" id="TAX" /></td>
<td></td>
</tr>
<td></td>
<td></td>
<tr>
<td></td>
<td align="right"><strong>Total $</strong></td>
<td><input type="text" name="TOTAL" id="TOTAL"></td>
<td></td>
</tr>
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'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 would like to prevent NaN from showing up in these text boxes: "total_full", "total_half", "total_single". I have tried setting the initial value of all calculating / number fields to "0", but "total_single" is still NaN until "check_out" date is selected and the total_days_acc is updated?
I am not sure how much of the code I am supposed to put here, and I would hate to leave something important out, so here is a link to a question where i incorrectly posted "all" the coding. :
hide / show fields based on input value
Thank you
<td>Accommodation:</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<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> </p></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> </td>
<td> </td>
<td> </td>
<td>Total Days Accommodation</td>
<td><input type="text" name="total_days_acc" id="total_days_acc" /></td>
</tr>
<tr>
<td>Number of Rooms:</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Single</td>
<td><input type="text" name="no_of_rooms_single" id="no_of_rooms_single" /></td>
<td> </td>
<td>Double / Twin</td>
<td><input type="text" name="no_of_rooms_double" id="no_of_rooms_double" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Contact Person</td>
<td><input type="text" name="contact_person" id="contact_person" /></td>
<td> </td>
<td> </td>
<td> </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> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Full Day Conference # R260.00 p/p</td>
<td><input type="text" name="full_day" id="full_day" /></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.00 p/p</td>
<td><input type="text" name="half_day" id="half_day" /></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.00 p/p</td>
<td><input type="text" name="single_rooms" id="single_rooms" /></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 # R720.00 p/p</td>
<td><input type="text" name="double_rooms" id="double_rooms" /></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.00 rental p/day</td>
<td><input type="text" name="data_proj" id="data_proj" /></td>
<td> </td>
<td>Total Cost Projector Rental</td>
<td><input name="total_project" type="text" id="total_project" readonly="readonly" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Sub Total</td>
<td><input type="text" name="sub_total" id="sub_total" /></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td height="23"> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</form>
</table>
</div>
<div id="hideme">
Hello Hideme
</div>
<p> </p>
<p> </p>
</body>
</html>
<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 = resultsingle;
}
$('#single_rooms').change(calculateSingle).keyup(calculateSingle);
$('#check_in_date').change(calculateSingle);
$('#check_out_date').change(calculateSingle);
//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>
Instead of just inserting the value into the page, just do this:
document.getElementById("total_days").value = isNaN(days) ? 0 : days;
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/