how to prevent isNaN before dates are selected in Datepicker - javascript

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;

Related

user have to either not input zip code and it should be of length 5(numbers only) but in my code else if statement line is not working

/* user have to either not input zip code and it should be of length 5(numbers only) but in my code else if statement line is not working. */
<script>
function max(){ /* this is the function to check the input feilds and if find mistake alert the message in to an alert box */
_aa=document.getElementById("s1").value
if(_aa.length>10)
xx="name should be less then or equal to 10 characters"
else xx=""
_bb=document.getElementById("s2").value
if(_bb.length>10)
yy="last name should be less then or equal to 10 characters"
else yy=""
_cc=document.getElementById("s3").value
if(_cc.length<6)
zz="street adress should be greater then or equal to 6 characters"
else zz=""
_dd=document.getElementById("s4").value
if(isNaN(_dd)){jj="fill"}
else if(_dd.length!=5 || _dd.length!=0){jj="fill"} \\this does'nt work
else{jj=""}
alert([xx,yy,zz,jj]);
}
</script>
<html>
<head>
<title>Form</title>
</head>
<body>
<form >
<table>
<tr>
<td colspan="2" align="middle">CHECKOUT FORM <hr/></td>
</tr>
<tr>
<td><strong>First name:</strong></td>
<td><input type="text"id="s1"/ ></td>
<td><p id="a1"></p></td>
</tr>
<tr>
<td><strong>Last name:</strong></td>
<td><input type="text"id="s2" / ></td>
<td><p id="a2"></p></td>
</tr>
<tr>
<td><strong>Street Address:</strong></td>
<td><input type="text"id="s3" maxlength="" / ></td>
<td><p id="a3"></p></td>
</tr>
<tr>
<td><strong>State:</strong></td>
<td><select><option>selet state</option></select></td>
</tr>
<tr>
<td><strong>Zip Code:</strong></td>
<td><input type="text" id="s4"></td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td><input type="number"id="s5" min="" max="" / ></td>
</tr>
</table>
<table>
<tr>
<td colspan="2" align="middle">ORDER INFORMATION <hr/></td>
</tr>
<tr>
<td><strong>Order Subtotal:</strong></td>
<td><input type="number"id="s6" min="" max="" / ></td>
</tr>
<tr>
<td><strong>Shipping Option:</strong></td>
<td><input type="radio"id="s7"value="6.75" name="bt" onclick="calculate(this.value)"/ >UPPS6.75</td>
</tr>
<tr>
<td></td>
<td><input type="radio"id="s8" value="8.55" name="bt" onclick="calculate(this.value)" / >UPS8.55</td>
</tr>
<tr>
<td></td>
<td><input type="radio"id="s9"value="10.00" name="bt" onclick="calculate(this.value)" / >FEDERAL EXPRESS10.00</td>
</tr>
<tr>
<td><strong>Shipping cost:</strong></td>
<td><input type="number"id="s10" min="" max="" / ></td>
</tr>
<tr>
<td><strong>Tax(5%):</strong></td>
<td><input type="number"id="s11" min="" max="" / ></td>
</tr>
<tr>
<td><strong>TOTAL:</strong></td>
<td><input type="number"id="s12" min="" max="" / ></td>
</tr>
</table>
<table>
<tr>
<td colspan="2" align="middle">PAYMENT INFORMATION <hr/></td>
</tr>
<tr>
<td><strong>Credit Card:</strong></td>
<td><input type="radio"id="s13"value="" name="bn" / >American Express</td>
</tr>
<tr>
<td></td>
<td><input type="radio"id="s14" value="" name="bn" / >Diners Club</td>
</tr>
<tr>
<td></td>
<td><input type="radio"id="s15"value="" name="bn" / >Discover</td>
</tr>
<tr>
<td></td>
<td><input type="radio"id="s16"value="" name="bn" / >MasterCard</td>
</tr>
<tr>
<td></td>
<td><input type="radio"id="s17"value="" name="bn" / >Visa</td>
</tr>
<tr>
<td><strong>Card Number:</strong></td>
<td><input type="number"id="s18" min="" max="" / ></td>
</tr>
<tr>
<td><strong>Expiration:</strong></td>
<td colspan="2"><select id="s19"><option>01</option></select>/
<select><option>2011</option></select>
</td>
</tr>
<tr>
<td><button type="button" onclick="max()" >place</button></td>
<td><input type="submit"id="s21" value="Cancel" / ></td>
</tr>
</table>
</body>
</html>
variable declaration was wrong
Declare all your element value in function start
And declare the all _aa with variable like var _aa
Don't forget to add {} in if else condition
Why is not working?
Because you are declare the _dd in if (_cc.length < 6) in else condition ._dd always null until if (_cc.length < 6) else statement execute
function max() {
var _aa = document.getElementById("s1").value
var _bb = document.getElementById("s2").value
var _cc = document.getElementById("s3").value
var _dd = document.getElementById("s4").value
if (_aa.length > 10) {
var xx = "name should be less then or equal to 10 characters"
} else {
xx = ""
}
if (_bb.length > 10) {
var yy = "last name should be less then or equal to 10 characters"
} else {
yy = "";
}
if (_cc.length < 6) {
var zz = "street adress should be greater then or equal to 6 characters"
} else {
zz = ""
}
if (isNaN(_dd)) {
var jj = "fill"
} else if (_dd.length != 5 || _dd.length != 0) {
jj = "fill length"
} else {
jj = ""
}
console.log([xx, yy, zz, jj]);
}
<form>
<table>
<tr>
<td colspan="2" align="middle">CHECKOUT FORM
<hr/>
</td>
</tr>
<tr>
<td><strong>First name:</strong></td>
<td><input type="text" id="s1" /></td>
<td>
<p id="a1"></p>
</td>
</tr>
<tr>
<td><strong>Last name:</strong></td>
<td><input type="text" id="s2" /></td>
<td>
<p id="a2"></p>
</td>
</tr>
<tr>
<td><strong>Street Address:</strong></td>
<td><input type="text" id="s3" maxlength="" /></td>
<td>
<p id="a3"></p>
</td>
</tr>
<tr>
<td><strong>State:</strong></td>
<td><select><option>selet state</option></select></td>
</tr>
<tr>
<td><strong>Zip Code:</strong></td>
<td><input type="text" id="s4"></td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td><input type="number" id="s5" min="" max="" /></td>
</tr>
</table>
<table>
<tr>
<td colspan="2" align="middle">ORDER INFORMATION
<hr/>
</td>
</tr>
<tr>
<td><strong>Order Subtotal:</strong></td>
<td><input type="number" id="s6" min="" max="" /></td>
</tr>
<tr>
<td><strong>Shipping Option:</strong></td>
<td><input type="radio" id="s7" value="6.75" name="bt" onclick="calculate(this.value)" />UPPS6.75</td>
</tr>
<tr>
<td></td>
<td><input type="radio" id="s8" value="8.55" name="bt" onclick="calculate(this.value)" />UPS8.55</td>
</tr>
<tr>
<td></td>
<td><input type="radio" id="s9" value="10.00" name="bt" onclick="calculate(this.value)" />FEDERAL EXPRESS10.00</td>
</tr>
<tr>
<td><strong>Shipping cost:</strong></td>
<td><input type="number" id="s10" min="" max="" /></td>
</tr>
<tr>
<td><strong>Tax(5%):</strong></td>
<td><input type="number" id="s11" min="" max="" /></td>
</tr>
<tr>
<td><strong>TOTAL:</strong></td>
<td><input type="number" id="s12" min="" max="" /></td>
</tr>
</table>
<table>
<tr>
<td colspan="2" align="middle">PAYMENT INFORMATION
<hr/>
</td>
</tr>
<tr>
<td><strong>Credit Card:</strong></td>
<td><input type="radio" id="s13" value="" name="bn" />American Express</td>
</tr>
<tr>
<td></td>
<td><input type="radio" id="s14" value="" name="bn" />Diners Club</td>
</tr>
<tr>
<td></td>
<td><input type="radio" id="s15" value="" name="bn" />Discover</td>
</tr>
<tr>
<td></td>
<td><input type="radio" id="s16" value="" name="bn" />MasterCard</td>
</tr>
<tr>
<td></td>
<td><input type="radio" id="s17" value="" name="bn" />Visa</td>
</tr>
<tr>
<td><strong>Card Number:</strong></td>
<td><input type="number" id="s18" min="" max="" /></td>
</tr>
<tr>
<td><strong>Expiration:</strong></td>
<td colspan="2"><select id="s19"><option>01</option></select>/
<select><option>2011</option></select>
</td>
</tr>
<tr>
<td><button type="button" onclick="max()">place</button></td>
<td><input type="submit" id="s21" value="Cancel" /></td>
</tr>
</table>

How to get a running total on a form with javascript

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

Using the same jQuery in multiple operations

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));
});
});

calculate sub total based on calculations

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/

Calculate the sum of products using a td attribute

I have this table :
<table>
<thead>
<tr>
<th>Quantity</th>
<th> </th>
<th>Price</th>
<th>Sum</th>
</tr></thead>
<tbody>
<tr class="sum">
<td><input class="qty" type="text" value="1" /></td>
<td>German format: </td>
<td data_price="1375.5">1.375,50 €</td>
<td></td>
</tr>
<tr class="sum">
<td><input class="qty" type="text" value="1" /></td>
<td>English format:</td>
<td data_price="1375.5">€1,375.50</td>
<td></td>
</tr>
<tr class="sum">
<td><input name="text" type="text" class="qty" value="1" /></td>
<td>French format:</td>
<td data_price="1375.5">1 375,50 €</td>
<td></td>
</tr>
<tr class="sum">
<td><input name="text2" type="text" class="qty" value="1" /></td>
<td>Italian format:</td>
<td data_price="1375.5">€1,375.50</td>
<td></td>
</tr>
<tr class="sum">
<td><input class="qty" type="text" value="1" /></td>
<td>Spanish format:</td>
<td data_price="1375.5">€ 1.375,50</td>
<td></td>
</tr>
<tr>
<td colspan="3">Total</td>
<td id="total"></td>
</tr>
</tbody>
</table>
and I want to use the value of attribute "data_price" to calculate the SUM like in this link :
http://jsfiddle.net/QmTNZ/77/
I want to use only the attribute "data_price" in calculation and not the .
Please help, I'm still beginner in jquery :)
For your price cells, you should use this format:
<td data-price="1375.5">€1,375.50</td>
i.e. with a hyphen, not underscore
You can then use:
$('td').data('price')
to access its value - see http://api.jquery.com/data
e.g.
var sum = 0;
$('.sum').each(function() {
var q = parseFloat($(this).find('.qty').val());
var p = parseFloat($(this).find('td').eq(2).data('price'));
sum += q * p;
});
$('#total').text(sum);
Working demo at http://jsfiddle.net/alnitak/gzYhN/
Try
var sum=0;
$('tbody > tr > td[data_price]').each(
function()
{
sum += parseFloat(this.attr('data_price'));
}
);
Try this: http://jsfiddle.net/ptfKJ/
This example is using your original HTML code.

Categories

Resources