why is the required attribute in the form not working - javascript

Html file: index.html. Had to validate with javascript because could not get required attribute to work. I did a sample file with a few fields and it worked, don't know why it is not working on this form. Please help.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Employee Cost</title>
<script src="js/jquery-2.2.4.min.js"></script>
<script src="js/nodep-date-input-polyfill.dist.js"></script>
<script src="js/moment.js"></script>
<script src="js/handlebars-v4.0.5.js"></script>
<script type="text/javascript" src="js/jquery.validate.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="css/hireCost.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.0.0.js"></script>
<script src="js/webshim/js-webshim/minified/polyfiller.js"></script>
<script>
webshim.activeLang('en');
webshims.polyfill('forms');
webshims.cfg.no$Switch = true;
</script>
</head>
<body>
<div id="text">
<div id="ribbon">
<ul>
<li>CPCC</li>
<li>Corporate & Continuing Education</li>
<li>CPCC Tix</li>
<li>CPCC Foundation</li>
<li class="accessibility">Accessibility</li>
<li class="need-help"><a href="http://www.cpcc.edu/services/need-help">Need Help
<img alt="Need Help?" src="http://www.cpcc.edu/++resource++theme.www.images/help_icon.png"></a></li>
</ul>
</div>
<div id="header-inner">
<div id="logo"><img src="http://www.cpcc.edu/++resource++theme.www.images/logo.png" alt="CPCC Logo"></div>
<div class="clear"></div>
</div>
<div class="LSResult" id="LSResult" style="">
<div class="LSShadow" id="LSShadow"></div>
</div>
<div id="menu">
<ul id="site-navigation">
<li id="portaltab-about" class="plain"><a href="http://www.cpcc.edu/about" title="">
About CPCC</a></li>
<li id="portaltab-learning" class="plain">Academics
</li>
<li id="portaltab-studentservices" class="plain"><a href="http://www.cpcc.edu/services" title="">Student
Services</a></li>
<li id="portaltab-artscommunity" class="plain"><a href="http://www.cpcc.edu/artscommunity" title="">Arts
& Community</a></li>
<li id="portaltab-careerhub" class="plain">Career Hub
</li>
</ul>
</div><!-- end menu -->
<noscript>
<h1 class="noScriptMessage"><b>We're sorry - You must have JavaScript enabled to use Rateschedule.</b></h1>
<h3 class="noScriptMessage">Please enable JavaScript on your browser.</h3>
</noscript>
<!-- Form data, all data is required, once submit is clicked, form will be validated and emcumbrance will be calculated. -->
<form id="calculation_form" name="calculation_form" method="post">
<h1>Rate Schedule Calculator</h1>
<fieldset>
<legend>Employee Information</legend>
<div class="help-info">
<strong>Note:</strong> Non-Exempt employees will submit and be paid from timesheets. Instructors will submit and be paid from contact hour reports.
</div>
<dl>
<dt><label for="empId">Employee ID:</label></dt>
<dd><input type="text" id="empId" pattern="[0-9]{7}" placeholder="Employee ID" value="" required />
</dd>
<dt><label for="fName">First Name:</label></dt>
<dd><input type="text" id="fName" required placeholder="First Name" value="" /></dd>
<dt><label for="lName">Last Name</label></dt>
<dd><input type="text" id="lName" required placeholder="Last Name" value="" /></dd>
<dt><label for="posNum">Position Number</label></dt>
<dd><input type="text" id="posNum" required placeholder="Position Number" value="" /></dd>
<dt><label for="posTitle">Position Title</label></dt>
<dd><input type="text" id="posTitle" required placeholder="Position Title" value="" /></dd>
<dt><label for="empType">Employee Type</label></dt>
<dd><select id="empType" name="empType">
<option value="" selected>Select Employee Type:</option>
<option value="Hourly Pay Rate (Non Exempt Employees)">Hourly Pay Rate (Non Exempt Employees)
</option>
<option value="Contact Hour Pay Rate (Exempt Instructors)">Contact Hour Pay Rate (Exempt
Instructors)
</option>
</select></dd>
<dt><label for="sDate">Start date</label></dt>
<dd><input type="date" id="sDate" required/></dd>
<dt><label for="cDate">End date</label></dt>
<dd><input type="date" id="cDate" required/></dd>
</dl>
</fieldset>
<fieldset>
<legend>Budgeting Worksheet</legend>
<div class="help-info">
<strong>Important:</strong> Be aware that submitting a rate sheet beyond the bounds of the current fiscal year will encumber funds for the following year.
</div>
<dl>
<dt><label for="glAcct">GL Account:</label></dt>
<dd><input type="text" id="glAcct" required placeholder="GL Account" value=""/></dd>
<dt><label for="rate">Hourly rate:</label></dt>
<dd><input type="number" id="rate" required placeholder="Hourly rate" value=""/></dd>
<dt><label for="hours">Estimated Monthly Hours:</label></dt>
<dd><input type="number" id="hours" required placeholder="Monthly Hours" value=""/></dd>
<dd><input type="hidden" id="comp" value=""/></dd>
</dl>
</fieldset>
<fieldset>
<legend>Supervisor Information</legend>
<div class="help-info">
Please enter the information for the supervisor of the position described in this Rate Schedule.
</div>
<dl>
<dt><label for="supervisor">Supervisor Name:</label></dt>
<dd><input type="text" id="supervisor" required placeholder="Supervisor Name" value=""/></dd>
<dt><label for="phone">Phone Extension:</label></dt>
<dd><input type="text" id="phone" pattern="[0-9]{4}" required placeholder="Phone Extension" value=""/>
</dd>
</dl>
</fieldset>
</form>
<p>
<button class="button" id="submit" value="submit">Calculate</button>
<button class="button" id="reset">Reset</button>
</p>
<div class="clear"></div>
<div id="footer">
<ul id="footer-navigation">
<li><a href="http://www.cpcc.edu/humanresources/employment">
<img src="http://www.cpcc.edu/++resource++theme.www.images/briefcase_icon.png"
alt="Jobs at CPCC"></a><br>
Jobs at CPCC</li>
<li><a href="http://www.cpcc.edu/attending/catalog">
<img src="http://www.cpcc.edu/++resource++theme.www.images/catalog_icon.png"
alt="College Catalog"></a><br>
College Catalog</li>
<li><a href="http://www.cpcc.edu/college-safety">
<img src="http://www.cpcc.edu/++resource++theme.www.images/icon_college_safety.png"
alt="College Safety"></a><br>
Safety</li>
<li><a href="http://www.cpcc.edu/site-map">
<img src="http://www.cpcc.edu/++resource++theme.www.images/sitemap_icon.png" alt="Site Map"></a><br>
Site Map</li>
<li><a href="http://inside.cpcc.edu/">
<img src="http://www.cpcc.edu/++resource++theme.www.images/employee_icon.png"
alt="Employee Intranet"></a><br>
Employee Intranet</li>
<li><a href="http://www.cpcc.edu/services/online-services">
<img id="tester" src="http://www.cpcc.edu/++resource++theme.www.images/globe_icon.png"
alt="Online Services"></a><br>
Online Services</li>
<li class="last">
<a href="http://www.cpcc.edu/contact-us">
<img src="http://www.cpcc.edu/++resource++theme.www.images/contact_icon.png"
alt="Contact Us"></a><br>
Contact Us</li>
</ul>
<div class="clear"></div>
<div id="footer-links">Supported Browsers /
Accessibility<br>Central Piedmont Community College
</div>
</div>
</div>
<!-- Below is the format for the printable form. Again Handlebars is used to update the page. -->
<div id="printable">
<div class="header-inner">
<div class="logo">
<img src="http://www.cpcc.edu/++resource++theme.www.images/logo.png" alt="CPCC Logo"/>
</div>
<div class="clear"></div>
</div>
<h3>Rate Schedule</h3>
<div class="help-employee-info">
<p>Note: Non-Exempt employees will submit and be paid from timesheets.
<br>Instructors will submit and be paid from contact hour reports.
</p>
</div>
<h3> Employee Information</h3>
<dl class="data">
<dt>Employee ID:</dt>
<dd>{{empId}}</dd>
<dt>First name:</dt>
<dd>{{fName}}</dd>
<dt>Last name:</dt>
<dd>{{lName}}</dd>
<dt>Position number:</dt>
<dd>{{posNum}}</dd>
<dt>Position title:</dt>
<dd>{{posTitle}}</dd>
<dt>Employee Type:</dt>
<dd>{{empType}}</dd>
</dl>
<h3>Budgeting Worksheet</h3>
<dl class="data">
<dt>GL Account:</dt>
<dd>{{glAcct}}</dd>
<dt>Start date:</dt>
<dd>{{sDate}}</dd>
<dt>End date:</dt>
<dd>{{cDate}}</dd>
<dt>Hourly rate:</dt>
<dd>{{rate}}</dd>
<dt>Estimated Monthly Hours:</dt>
<dd>{{hours}}</dd>
</dl>
<h3>Calculated Values</h3>
<dl class="data">
<dt>Estimated Encumbrance for Current Fiscal Year:</dt>
<dd>{{comp}}</dd>
</dl>
<div>
<h3>Authorization:</h3>
<div class="signature-box"></div>
<div id="supervisor-print">
<span>{{supervisor}}</span>
<span>Phone Extension: {{phone}}</span>
<span>Date</span>
</div>
<div class="help-employee-info">
<p>Please sign, date and submit to Human Resources.</p>
</div>
</div>
</div>
<script src="calculateHireCost.js">
</script>
</body>
</html>
Javascript file: calculateHireCost.js
// This program will calculate the cost of hiring personal for the dates, rate, and hours specified. The program will
// also retain values for a print friendly page once the calculate/submit button is pressed. Handlebars is used to
// update the page with the printable version of the information.
// Run fuction validateForm when the submit button is clicked. Once the form is validated, ValidateForm will call the
// function process_form. The only validation is that a field is required and end date is greater than start date.
// Run function reset_form when reset button is clicked.
$("#submit").bind( "click", function() { validateForm() });
$("#reset").bind( "click", function() { reset_form() });
var source = $("#printable").html();
var template = Handlebars.compile(source);
$(document).ready(function()
{
$('#sDate').val("");
$('#cDate').val("");
initialize_dates();
})
// Validate fields to confirm no null values. If field is blank or null, return alert message requesting input from
// the user. If all fields are valid, run process_form.
function validateForm() {
var empId = document.forms["calculation_form"]["empId"].value;
var fName = document.forms["calculation_form"]["fName"].value;
var lName = document.forms["calculation_form"]["lName"].value;
var posNum = document.forms["calculation_form"]["posNum"].value;
var posTitle = document.forms["calculation_form"]["posTitle"].value;
var empType = document.forms["calculation_form"]["empType"].value;
var sDate = document.forms["calculation_form"]["sDate"].value;
var cDate = document.forms["calculation_form"]["cDate"].value;
var glAcct = document.forms["calculation_form"]["glAcct"].value;
var rate = document.forms["calculation_form"]["rate"].value;
var hours = document.forms["calculation_form"]["hours"].value;
var supervisor = document.forms["calculation_form"]["supervisor"].value;
var phone = document.forms["calculation_form"]["phone"].value;
if (empId == null || empId == "") {
alert("Employee Id must be entered");
return false;
}
if (fName == null || fName == "") {
alert("First name must be entered");
return false;
}
if (lName == null || lName == "") {
alert("Last name must be entered");
return false;
}
if (posNum == null || posNum == "") {
alert("Position number must be entered");
return false;
}
if (posTitle == null || posTitle == "") {
alert("Position title must be entered");
return false;
}
if (empType == null || empType == "") {
alert("Employee Type must be entered");
return false;
}
if (sDate == null || sDate == "") {
alert("A start date must be selected");
return false;
}
if (cDate == null || cDate == "") {
alert("An end date must be selected");
return false;
}
if (glAcct == null || glAcct == "") {
alert("GL Account must be entered");
return false;
}
if (rate == null || rate == "") {
alert("An hourly rate must be entered");
return false;
}
if (hours == null || hours == "") {
alert("The estimated monthly hours must be entered");
return false;
}
if (supervisor == null || supervisor == "") {
alert("Supervisor's name must be entered");
return false;
}
if (phone == null || phone == "") {
alert("Phone extension must be filled out");
return false;
}
process_form();
}
// process_form will save entered and calculated values to be re-displayed in a print friendly form
// on the page. This function will call the calculate function to calculate the Yearly Emcumbrance.
function process_form()
{
var empId = $("#empId").val();
var fName = $("#fName").val();
var lName = $("#lName").val();
var posNum = $("#posNum").val();
var posTitle = $("#posTitle").val();
var empType = $("#empType").val();
var glAcct = $("#glAcct").val();
var sDate = $("#sDate").val();
var cDate = $("#cDate").val();
var rate = $("#rate").val();
var hours = $("#hours").val();
var supervisor = $("#supervisor").val();
var phone = $("#phone").val();
console.log(sDate);
console.log(cDate);
console.log(hours);
console.log(rate);
// verify end date is greater than start date.
if (sDate < cDate)
{
// store compensation
$("#comp").val(calculate(sDate, cDate));
var comp = $("#comp").val();
// data variable will be used by handlebars to create printable version of page.
var data = {
'empId': empId,
'fName': fName,
'lName': lName,
'posNum': posNum,
'posTitle': posTitle,
'empType': empType,
'glAcct': glAcct,
'sDate': sDate,
'cDate': cDate,
'rate': rate,
'hours': hours,
'comp': comp,
'supervisor': supervisor,
'phone': phone,
}
console.log(sDate);
console.log(cDate);
console.log(hours);
console.log(rate);
// replace div id=="text" with printable version of "data".
document.getElementById('text').innerHTML = template(data);
}
else
{
alert('End date must be later than start date. Please adjust dates.');
}
}
// This function will calculate the yearly encumbrance. The number of hours x rate x months. The months between
// function will determine the number of months.
function calculate(sDate,cDate)
{
// convert date string to date
var newdate1 = new Date(sDate);
var newdate2 = new Date(cDate);
newdate1.setDate(newdate1.getDate() + 2);
newdate2.setDate(newdate2.getDate() + 2);
var dd1 = newdate1.getDate();
var mm1 = newdate1.getMonth() + 1;
var y1 = newdate1.getFullYear();
var dd2 = newdate2.getDate();
var mm2 = newdate2.getMonth() + 1;
var y2 = newdate2.getFullYear();
var date1 = mm1 + '-' + dd1 + '-' + y1;
var date2 = mm2 + '-' + dd2 + '-' + y2;
var date1 = new Date(date1);
var date2 = new Date(date2);
date1 = moment(date1).format('YYYY-MM-DD');
date2 = moment(date2).format('YYYY-MM-DD');
var rate = $("#rate").val();
var hours = $("#hours").val();
console.log(date1);
console.log(date2);
// retrieve number of months
var months = monthsBetween(date1, date2);
console.log(months);
// calculate total hours and compensation
var comp = rate * hours * months;
console.log(comp);
return comp;
}
// This function calculates the number of months between the two dates. Partial months will be counted as
// a whole month. If the end date is 8/1/20xx, then August will count as one month. Since this is for
// yearly budgeting, the number of months have a max of 12. If a two year period is entered, it will be
// reduced from 24 to 12 months.
function monthsBetween(date1, date2)
{
date1 = new Date(date1);
date2 = new Date(date2);
var date1Month = date1.getMonth();
var date2Month = date2.getMonth();
var date1Year = date1.getFullYear();
var date2Year = date2.getFullYear();
var date2Date = date2.getDate();
var months = 0;
if (date1 < date2) {
var i = new Date(date1);
while ((i <= date2) && (months < 12)) {
if (date1Month == 11) {
months++;
date1Year++;
date1Month = 00;
i.setDate(01);
i.setFullYear(date1Year);
i.setMonth(00);
}
else {
months++;
date1Month++;
i.setDate(01);
i.setMonth(date1Month);
}
}
}
else
{
alert('End date must be later than start date. Please adjust dates.');
}
if (months == 0)
{
months = 1;
}
if (date2Date == 01)
{
months++;
}
if (months > 12)
{
months = 12;
}
return months;
}
function reset_form()
{
$("#empId").val("");
$("#fName").val("");
$("#lName").val("");
$("#posNum").val("");
$("#posTitle").val("");
$("#empType").val("");
$("#glAcct").val("");
$("#sDate").val("");
$("#cDate").val("");
$("#rate").val(0);
$("#hours").val(0);
$("#comp").val(0);
$("#supervisor").val("");
$("#phone").val("");
initialize_dates();
}
function set_end_date_per_start_date(mode) {
//
// Seed the end date based on the start date's month. If after May, push
// the end date's year out to next year.
//
if (mode == 'initial')
{
startDate = new Date();
console.log(startDate);
}
else
{
currentStartDate = $("#sDate").val();
console.log(currentStartDate);
parts = currentStartDate.value.split("/");
startDate = new Date(parseInt(parts[2]),(parseInt(parts[0])),parseInt(parts[1]));
console.log(startDate);
}
if (startDate.getMonth() > 4)
{
console.log(startDate);
endDate = new Date((startDate.getFullYear() + 1), 4, 31);
console.log(endDate);
}
else
{
endDate = new Date(startDate.getFullYear(), 4, 31);
console.log(endDate);
}
console.log(startDate.getMonth());
console.log(startDate.getDate());
startDateString = moment(startDate).format('YYYY-MM-DD');
$("#sDate").val(startDateString);
console.log($("#sDate").val());
console.log(startDate.getMonth());
console.log(startDate.getDate());
console.log(endDate.getMonth());
console.log(endDate.getDate());
endDateString = moment(endDate).format('YYYY-MM-DD');
$("#cDate").val(endDateString);
console.log($("#cDate").val());
console.log(endDate.getMonth());
console.log(endDate.getDate());
}
function initialize_dates() {
//
// Seed with today's date.
//
set_end_date_per_start_date('initial');
}

Related

Thymeleaf - Add leading zero to date field if day or month is entered as D/M instead of DD/MM

I have this code for date entry in a Thymeleaf template:
<div class="m-form-row__content">
<ul class="m-textbox-group" data-module="a-autojump">
<li class="m-textbox-group__item"><label
class="m-textbox-group__item-label" for="pHolder.dobDay">Day</label>
<input type="text" id="pHolder.dobDay"
th:field="*{pHolder.dobDay}" placeholder="DD"
class="a-textbox a-textbox--2-character" maxlength="2" /></li>
<li class="m-textbox-group__item"><label
class="m-textbox-group__item-label" for="pHolder.dobMonth">Month</label>
<input type="text" id="pHolder.dobMonth"
th:field="*{pHolder.dobMonth}" placeholder="MM"
class="a-textbox a-textbox--2-character" maxlength="2" /></li>
<li class="m-textbox-group__item"><label
class="m-textbox-group__item-label" for="pHolder.dobYear">Year</label>
<input type="text" id="pHolder.dobYear"
th:field="*{pHolder.dobYear}" placeholder="YYYY"
class="a-textbox a-textbox--4-character" maxlength="4" /></li>
</ul>
</div>
The date format should be DD/MM/YYYY but currently if something like D/M/YYYY is entered no validation catches this and it causes an error in a downstream application. I'd like to add some functionality where a leading zero is added if the length of D or M are 1.
An example of what I'm trying to do but done with JSP and JavaScript are as follows:
<div class="input">
<div class="textfield inputGroup">
<form:input path="proposer.dobDay" id="proposer.dobDay"
cssClass="input-text small dayfield only-digits validateFrontend" size="3" maxlength="2"
onkeyup="moveOnMaxDob(this,'proposer.dobMonth')" onchange="joinDOBVal()" />
<form:input path="proposer.dobMonth" id="proposer.dobMonth"
cssClass="input-text small monthfield only-digits validateFrontend" size="3" maxlength="2"
onkeyup="moveOnMaxDob(this,'proposer.dobYear')" onchange="joinDOBVal()"/>
<form:input path="proposer.dobYear" id="proposer.dobYear"
cssClass="input-text small yearfield only-digits validateFrontend" size="5" maxlength="4"
onchange="joinDOBVal()"/>
<span class="validIcon"></span>
<div class="errorContainerContact"></div>
<!-- hidden fields for full dob -->
<form:hidden path="proposer.dob" id="proposer.dob"/>
</div>
<div class="errorContainer dob">
<form:errors path="proposer.dob" cssClass="field-validation-error" htmlEscape="false" />
</div>
</div>
function joinDOBVal() {
var day = document.getElementById("proposer.dobDay").value;
var month = document.getElementById("proposer.dobMonth").value;
var year = document.getElementById("proposer.dobMonth").value;
if (IsNumeric(day) == true && IsNumeric(month) == true
&& IsNumeric(year) == true) {
if(day != "" && day.length == 1 && day != "0") {
day = "0"+day;
document.getElementById("proposer.dobDay").value = day;
}
if(month != "" && month.length == 1 && month != "0") {
month = "0"+month;
document.getElementById("proposer.dobMonth").value = month;
}
if ((year != "") && (year.length == 4)) {
var fullDob = day + "/" + month + "/" + year;
document.getElementById("proposer.dob").value = fullDob;
} else {
document.getElementById("proposer.dob").value = "";
}
} else {
document.getElementById("proposer.dob").value = "";
}
}
Think maybe I could do something along the lines of but not quite this:
<input th:if="${policyHolder.dobDay.count} > 1" type="text" id="pHolder.dobDay"
th:field="*{pHolder.dobDay}" placeholder="DD"
class="a-textbox a-textbox--2-character" maxlength="2" />
<input th:if="${policyHolder.dobDay.count} &eq; 1" type="text" id="pHolder.dobDay"
th:field="0*{pHolder.dobDay}" placeholder="DD"
class="a-textbox a-textbox--2-character" maxlength="2" />
Update
My understanding is that the label passes the value to input e.g. for="policyHolder.dobDay" and id="policyHolder.dobDay". Is it possible to do some sort of th:if in the label so the desired value is passed to be input?

Transferring data between HTML pages doesn't seem to work?

I am currently working with forms and javascript validation.. i have completed most of my code and am on the last step however cant seem to get it working and not sure what ive done wrong.. spent hours on this last part before i looked for help.
basically a user inputs their information into a form and then when they click submit the information get validated, and the inputed info moves onto a confirmation page.. at the moment the input i put in doesnt get validated anymore and is blank in the confirmation page..
First HTML register page
<form id="regform" method="post" action="confirm.html"
novalidate="novalidate">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="firstname">Enter your first name</label>
<input type="text" name="firstname" id="firstname" size="20"
/>
</p>
<p><label for="lastname">Enter your last name</label>
<input type="text" name="lastname" id="lastname" size="20" />
</p>
<fieldset id="species">
<legend>Species:</legend>
<label for="human">Human</label>
<input type="radio" name="species" id="human"
value="Human"/><br />
<label for="dwarf">Dwarf</label>
<input type="radio" name="species" id="dwarf"
value="Dwarf" /><br />
<label for="elf">Elf</label>
<input type="radio" name="species" id="elf"
value="Elf" /><br />
<label for="hobbit">Hobbit</label>
<input type="radio" name="species" id="hobbit"
value="Hobbit" /><br />
</fieldset>
<p><label for="age">Enter your age</label>
<input type="text" id="age" name="age" size="5">
</p>
</fieldset>
<fieldset id="trip">
<legend>Your trip:</legend>
<fieldset>
<legend>Booking:</legend>
<label for="1day">1 Day Tour - $200 </label>
<input type="checkbox" name="1day" id="1day"
value="1day" /><br />
<label for="4day">4 Day Tour - $1500</label>
<input type="checkbox" name="4day" id="4day"
value="4day" /><br />
<label for="10day">10 Day Tour - $3000</label>
<input type="checkbox" name="10day" id="10day"
value="10day" /><br />
</fieldset>
<p>
<label for="food">Menu preferences</label>
<select name="food" id="food">
<option value="none">Please select</option>
<option value="lembas">Lembas</option>
<option value="mushrooms">Mushrooms</option>
<option value="ent">Ent Draft</option>
<option value="cram">Cram</option>
</select>
</p>
<p>
<label for="partySize">Number of Travellers</label>
<input type="text" id="partySize" name="partySize" maxlength="3"
size="3" />
</p>
</fieldset>
<div id="bottom"> </div>
<p><input type="submit" value="Book Now!" />
<input type="reset" value="Reset" />
</p>
Validation for Javascript
function validate() {
var errMsg = "";
var result = true;
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
if (!firstname.match(/^[a-zA-Z]+$/)) {
errMsg = errMsg + "Your first name must only contain alpha characters\n";
result = false;
}
if (!lastname.match(/^[a-zA-Z+$]/)) {
errMsg = errMsg + "Your last name must only contain alpha characters\n";
result = false;
}
var age = document.getElementById("age").value;
if (isNaN(age)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (age < 18) {
errMsg = errMsg + " your age must be 18 or older\n";
result = false;
}
else if (age >= 10000) {
errMsg = errMsg + "your age must be between 18 and 10000\n";
result = false;
}
else {
var tempMsg = checkSpeciesAge(age);
if (tempMsg != "") {
errMsg + tempMsg;
result = false;
}
var partySize = document.getElementById("partySize").value;
if (isNaN(partySize)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (partySize < 1) {
errMsg = errMsg + " party size must be greater than 0\n";
result = false;
}
else if (age >= 100) {
errMsg = errMsg + "your party size must be less or equal to 100\n";
result = false;
}
}
var is1day = document.getElementById("1day").checked;
var is4day = document.getElementById("4day").checked;
var is10day = document.getElementById("10day").checked;
if (!(is1day || is4day || is10day)) {
errMsg = errMsg + "please select at least one trip.\n";
result = false;
}
if (document.getElementById("food").value == "none") {
errMsg = errMsg + "You must select a food preference. \n ";
result = false;
}
var human = document.getElementById("human").checked;
var dwarf = document.getElementById("dwarf").checked;
var elf = document.getElementById("elf").checked;
var hobbit = document.getElementById("hobbit").checked;
if (!(human || dwarf || elf || hobbit)) {
errMsg = errMsg + "please select a spiecies";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
if (result) {
storeBooking(firstname, lastname, age, species, is1day, is4day, is10day);
}
return result;
}
function getSpecies() {
var speciesName = "Unknown";
var speciesArray = document.getElementById("species").getElementsByTagName("input");
for (var i = 0; i < speciesArray.length; i++){
if (speciesArray[i].checked)
speciesName = speciesArray[i].value;
}
return speciesName;
}
function checkSpeciesAge(age) {
var errMsg = "";
var species = getSpecies();
switch(species){
case "human":
if (age > 120) {
errMsg = "you cannot be a Human and over 120. \n";
}
break;
case "dwarf":
case "hobit":
if (age > 150 ){
errMsg = " YOu can not be a " + species + " and over 150 .\n ";
}
break;
case "elf":
break;
default:
errMsg = " we dont allow your kind on our tours. \n";
}
return errMsg;
}
function storeBooking(firstname, lastname, age, species, is1day, is4day, is10day){
var trip= "";
if(is1day) trip ="1day";
if(is4day) trip +=", 4day";
is(is10day) trip += ", 10day";
sessionStorage.trip = trip;
sessionStorage.firstname= firstname;
sessionStorage.lastname= lastname;
sessionStorage.age = age;
sessionStorage.species= species;
sessionStorage.partySize= partySize;
sessionStorage.food = food;
alert ("Trip stored: " + sessionStorage.trip);
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
Confirm HTML
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking" />
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
Javascrips file 2 to bring the info over to the confirmation
function validate(){
var errMsg = "";
var result = true;
return result;
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function getBooking(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
There are a couple of syntax errors that should be clearly visible when you open your browser console:
- errMsg + tempMsg; is not a complete statement,
- is(is10day) trip += ", 10day"; is not valid, and
- storeBooking doesn't have a parameter called partySize
I see a couple of logic errors too:
- checkSpeciesAge will never return an empty string as validate expects, and
- the section of code that attempts to validate partySize has several errors (including that this entire structure is nested inside the age-validation section's else block.)
A few console.log statements could go a long way toward identifying where your variables contain values that you don't expect if there are still bugs to track down after correcting these issues. Good luck!
I tried to fix this, and make some changes in your code. according to your requirement
follow the link of jsfiddle; https://jsfiddle.net/dupinderdhiman/vno15jku/32/
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking"/>
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
<script>
sessionStorage.trip = "4day";
sessionStorage.firstname= "firstname";
sessionStorage.lastname= "lastname";
sessionStorage.age = 21;
sessionStorage.species= "species";
sessionStorage.partySize= 10;
sessionStorage.food = "food";
function validate(){
var errMsg = "";
var result = true;
return result;
}
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function loadDataFromSession(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
loadDataFromSession();
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
</script>
so what is the major change:
Created one function loadDataFromSession which call on init();
remove code from getBooking() add to loadDataFromSession.
now click on submit and your form will be submit

Trying to remove each line of HTML element using a newly created button

var Operator = document.getElementById("operation");
var Desc = document.getElementById("description");
var Amount = document.getElementById("value");
var budget = 0.00;
var income = 0.00;
var expenses = 0.00;
var IncomeList = document.getElementById("incomeList");
var ExpenseList = document.getElementById("expenseList");
document.getElementById("submit").addEventListener("click", function() {
var DButton = document.createElement("button");
var t = document.createTextNode("Delete");
//document.body.appendChild(DButton);
DButton.appendChild(t);
// Converts the fake (non-existant)numbers into real (functionable) numbers
var aValue = parseFloat(Amount.value);
// if the operator is +, budget and income will increase by whatever you type in the value
if (Operator.value == "+") {
budget = budget += aValue;
income = income += aValue;
// The value that was typed along with description in will appear in the Income list in each line
IncomeList.innerHTML = IncomeList.innerHTML + Desc.value + ": " + aValue;
IncomeList.appendChild(DButton);
IncomeList.innerHTML = IncomeList.innerHTML + "<br>";
} else {
budget = budget -= aValue;
expenses = expenses -= aValue;
ExpenseList.innerHTML = ExpenseList.innerHTML + Desc.value + ": " + aValue;
ExpenseList.appendChild(DButton);
ExpenseList.innerHTML = ExpenseList.innerHTML + "<br>";
}
// Declaring statements to make it easier to input
document.getElementById("budget").innerText = budget;
document.getElementById("incomeTotal").innerText = income;
document.getElementById("expenseTotal").innerText = expenses;
});
<div id="wrapper">
<div id="top">
<p id="day">Available Budget in January 2018:</p>
<p id="budget">0.00</p>
<div id="income" class="highlight">
<h1>Income</h1>
<p id="incomeTotal">+0.00</p>
</div>
<div id="expenses" class="highlight">
<h1>Expenses</h1>
<p id="expenseTotal">-0.00</p>
</div>
</div>
<div id="controls">
<select id="operation">
<option>+</option>
<option>-</option>
</select>
<input type="text" placeholder="Add description" id="description" required/>
<input type="number" min="1" placeholder="Value" id="value" />
<button id="submit">✓</button>
</div>
<div id="content">
<div id="incomeList">
<p>INCOME</p>
</div>
<div id="expenseList">
<p>EXPENSES</p>
</div>
</div>
</div>
Hi, this is a budget tracker I made to practice JavaScript. So whenever users type a description and an amount and press submit, the list will show up along with a delete button that erases each line. How should I approach this method? Because the button is newly created by createElement, I do not know how to make this a handler...Thank you.
Append a row container instead of concatenating to the HTML string, and then you can attach a listener to the button that calls .remove() on the row.
It's often a good idea to avoid assigning to innerHTML when possible - it will corrupt all existing Javascript references to any elements inside. If you want to assign text alone, use textContent rather than innerHTML or createTextNode. (it's faster, safer, and more predictable)
var Operator = document.getElementById("operation");
var Desc = document.getElementById("description");
var Amount = document.getElementById("value");
var budget = 0.00;
var income = 0.00;
var expenses = 0.00;
var incomeList = document.getElementById("incomeList");
var expenseList = document.getElementById("expenseList");
document.getElementById("submit").addEventListener("click", function() {
const parent = Operator.value === "+" ? incomeList : expenseList;
const row = parent.appendChild(document.createElement('div'));
var DButton = row.appendChild(document.createElement("button"));
DButton.textContent = 'delete';
DButton.onclick = () => row.remove();
var aValue = parseFloat(Amount.value);
row.appendChild(document.createTextNode(Desc.value + ": " + aValue));
if (Operator.value == "+") {
budget = budget += aValue;
income = income += aValue;
} else {
budget = budget -= aValue;
expenses = expenses -= aValue;
}
// Declaring statements to make it easier to input
document.getElementById("budget").innerText = budget; document.getElementById("incomeTotal").innerText = income; document.getElementById("expenseTotal").innerText = expenses;
});
<div id="wrapper">
<div id="top">
<p id="day">Available Budget in January 2018:</p>
<p id="budget">0.00</p>
<div id="income" class="highlight">
<h1>Income</h1>
<p id="incomeTotal">+0.00</p>
</div>
<div id="expenses" class="highlight">
<h1>Expenses</h1>
<p id="expenseTotal">-0.00</p>
</div>
</div>
<div id="controls">
<select id="operation">
<option>+</option>
<option>-</option>
</select>
<input type="text" placeholder="Add description" id="description" required/>
<input type="number" min="1" placeholder="Value" id="value" />
<button id="submit">✓</button>
</div>
<div id="content">
<div id="incomeList">
<p>INCOME</p>
</div>
<div id="expenseList">
<p>EXPENSES</p>
</div>
</div>
</div>

Vehicle Rental Rate Calculation

Trying with the booking and vehicle rental calculation.
Calendar should disable already booked date (Done - used datepicker beforeShowDay:)
For Weekends, Friday and Monday should select for collection and return (Done - )
Now comes the calculation (Issue)
Rates are based on Fig1. From Fig1, I extracted few scenarios Fig3 for programming.
The Rental Fee calculates based on the Start and End Dates.
If user choose
Mon-Fri follows Weekday rate
Fri-Mon follows Weekend Rate
Mon-Mon/Tue-Tue/Wed-Wed/Thu-Thu/Fri-Fri follows weekly rate
1st of a month and 1st of second month follows monthly package
If user chooses
Any day to another day of a far week, the rates should mix the packages based on the date's selected
Problem
I was doing the javascript calculations and stucked in the last point of above.
Stackoverflow
Found few, but not the above scenarios, some are just simple direct calculation from start date to end date.
HTML-Javascript and My Tries
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vehicle Rental Booking Calculation</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<style type="text/css">
td.red span.ui-state-default {
color: #f00;
font-weight:normal;
}
td.green span.ui-state-default {
color: #0f0;
}
</style>
<script type="text/javascript">
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
$(function() {
var array = ["2016-07-26","2016-08-17","2016-08-18","2016-08-19","2016-08-20","2016-08-30","2016-08-31","2016-09-01","2016-09-02","2016-09-15","2016-09-16","2016-09-17","2016-09-20","2016-09-21","2016-09-22","2016-10-05","2016-10-06","2016-10-07","2016-10-12","2016-10-13","2016-10-14","2016-11-17","2016-11-18","2016-11-19","2016-11-20","2016-11-21","2016-11-22"];
$(".datepicker").datepicker({
showOtherMonths: false,
selectOtherMonths: true,
dateFormat : "dd-mm-yy",
minDate: 0,
maxDate: "+12M +10D",
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
//alert(date+" "+array.indexOf(string));
var day = date.getDay();
if (array.indexOf(string) != -1)
{
return [ array.indexOf(string) == -1, 'holiday red', jQuery.datepicker.formatDate('dd-mm-yy', date) + ' is booked' ];
}
else
{
if (day == 0 || day == 6)
return [array.indexOf(string) == -1, '', 'For the Saturday or Sunday selection, the start date (Collection) should be before Saturday and end date (Return) should be after Sunday.\n\nFor weekend package: \nWeekend is from Fri to Mon [Total 2 days], Collection is on Friday and Return is on Monday.'];
else
return [ array.indexOf(string) == -1 ];
}
},
onSelect: function(dateText, inst) {
$(this).data('datepicker').inline = false;
var obj_id = $(this).attr("id");
if (obj_id == "start_date" || obj_id == "end_date")
{
// Weekend select STARTS
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var dt = new Date(dateText.replace(pattern,"$3-$2-$1"));
var day = dt.getDay();
if (day == 0 || day == 6)
{
alert("For the Saturday or Sunday selection, the start date (Collection) should be before Saturday and end date (Return) should be after Sunday.\n\nFor weekend package: \nWeekend is from Fri to Mon [Total 2 days], Collection is on Friday and Return is on Monday.");
$(this).val("");
$(this).data('datepicker').inline = true;
}
// Weekend select ENDS
// Calculation STARTS
var calc_flag = 1;
var start_date = $("#start_date").val();
var end_date = $("#end_date").val();
if (start_date == "" || end_date == "")
calc_flag = 0;
// Get the vehicle rates
var hid_daily_rate = $("#hid_daily_rate").val();
var hid_weekend_rate = $("#hid_weekend_rate").val();
var hid_weekly_rate = $("#hid_weekly_rate").val();
var hid_monthly_rate = $("#hid_monthly_rate").val();
var rental_fee = 0;
// Testing STARTS
if (calc_flag)
{
// get the start and end date
var dateStart = $("#start_date").datepicker("getDate");
var dateEnd = $("#end_date").datepicker("getDate");
var totalmonths = monthDiff(dateStart, dateEnd);
var totalmonths1 = dateEnd.getMonth() - dateStart.getMonth() + (12 * (dateEnd.getFullYear() - dateStart.getFullYear()));
var totalDays = (dateEnd - dateStart) / 24 / 60 / 60 / 1000; //get total days
console.log(dateStart+"\n"+dateEnd+"\ntotalmonths="+totalmonths+","+totalmonths1+" totalDays="+totalDays);
}
// Testing ENDS
if (calc_flag)
{
var a = $("#start_date").datepicker("getDate").getTime(),
b = $("#end_date").datepicker("getDate").getTime(),
c = 24*60*60*1000,
diffDays = Math.round(Math.abs((a - b)/(c)));
//console.log(diffDays); //show difference
//alert(diffDays);
rental_fee = hid_daily_rate*diffDays;
$("#rental_fee").html('$'+rental_fee);
}
// Calculation ENDS
}
}
});
});
</script>
</head>
<div class="container">
<div class="col-lg-12 col-xs-offset-1"><h2 style="text-decoration:underline;">Booking Form</h2></div>
<div class="col-lg-12 col-xs-offset-1">
<div class="alert-info" style="width:600px;">
<ul>
<li>Daily Rate (Mon to Fri) <span>: <strong>$75</strong></span> <br/>- Weekday (Mon - Fri), Min 2days is required</li>
<li>Weekend Rate <span>: <strong>$290</strong></span> <br/> - Weekend Package (Fri - Mon)</li>
<li>Weekly Rate <span>: <strong>$490</strong></span> <br/> - Weekly Package</li>
<li>Monthly Rate <span>: <strong>$1860</strong></span> <br/> - Monthly Package</li>
</ul>
</div>
</div>
<form role="form" class="form-horizontal" method="POST" action="booking_action.php" id="frmBookingFormAction" name="frmBookingFormAction">
<input type="hidden" value="17" name="vehicle_id" id="vehicle_id">
<input type="hidden" id="hid_daily_rate" name="hid_daily_rate" value="75" />
<input type="hidden" id="hid_weekend_rate" name="hid_weekend_rate" value="290" />
<input type="hidden" id="hid_weekly_rate" name="hid_weekly_rate" value="490" />
<input type="hidden" id="hid_monthly_rate" name="hid_monthly_rate" value="1860" />
<div class="form-group">
<label for="start_date" class="control-label col-sm-3">Start Date <label class="clr_error">*</label></label>
<div class="col-sm-5">
<input type="text" autocomplete="off" placeholder="dd-mm-yy" value="" name="start_date" id="start_date" class="form-control datepicker">
</div>
</div>
<div class="form-group">
<label for="end_date" class="control-label col-sm-3">End Date <label class="clr_error">*</label></label>
<div class="col-sm-5">
<input type="text" autocomplete="off" placeholder="dd-mm-yy" value="" name="end_date" id="end_date" class="form-control datepicker">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="collection_time">Collection and Return Time </label>
<div class="col-sm-5">
<select id="collection_time" name="collection_time" class="form-control">
<option value="0">[Select]</option>
<option value="10:00">10:00 am</option>
<option value="11:00">11:00 am</option>
<option value="12:00">12:00 pm</option>
<option value="13:00">1:00 pm</option>
<option value="14:00">2:00 pm</option>
<option value="15:00">3:00 pm</option>
<option value="16:00">4:00 pm</option>
<option value="17:00">5:00 pm</option>
<option value="18:00">6:00 pm</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">Rental Fee</label>
<div class="col-sm-5">
<p class="form-control-static"><strong>: <span id="rental_fee">$00.00</span></strong></p>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-8">
<input type="button" class="btn btn-primary" value="Continue" name="btnSubmit" id="btnSubmit">
</div>
</div>
</form>
</div>
S C R E E N S H O T S
Aug-Sep Calendar for testing and Rental Rates
Fig1
Booking Form and Calculation
Fig2
Calculation Equation Samples
Fig3
Working Fiddle
Thanks in advance
JSFiddle
Relevant Code
if (calc_flag) {
// get the start and end date
var dateStart = $("#start_date").datepicker("getDate");
var dateEnd = $("#end_date").datepicker("getDate");
// Add months to the rental fee, and move the date forward
var months = monthDiff(dateStart, dateEnd);
var currDate = addMonths(dateStart, months);
rates.monthly = months;
// Add weeks to the rental fee, and move the date forward
var days = (dateEnd - dateStart) / 24 / 60 / 60 / 1000;
var weeks = Math.floor(days / 7);
currDate.setTime(currDate.getTime() + weeks * 7 * 24 * 60 * 60 * 1000);
rates.weekly = weeks;
// Calculate the daily rate, noting conflict with
// weekend rate
var dDays = dateEnd.getDay() - currDate.getDay();
if (dDays < 0) dDays += 7;
rates.daily += dDays;
// If it loops around, readjust for weekend rate
if (currDate.getDay() > dateEnd.getDay()) {
rates.daily -= 3;
rates.weekend += 1;
}
console.log(rates);
rental_fee = rates.monthly * hid_monthly_rate +
rates.weekly * hid_weekly_rate +
rates.weekend * hid_weekend_rate +
rates.daily * hid_daily_rate;
// Update the interface
$("#rental_fee").html('$'+rental_fee);
}
Explanation
There are two types of rates in this problem:
Duration rates (monthly, weekly and daily)
Specific rates (weekend)
To calculate duration rates, you work from the largest interval to the smallest interval, working out how many of each interval will 'fit' within the time period. For example, in 9 days, you can fit 0 whole months, 1 whole week and 2 whole days.
The complexity of the problem arises when you consider the weekend rate. You must know the concerned days to be able to determine if it is appropriate to allocate the weekend rate or the daily rate.
To solve this, you can calculate remaining days after the monthly and weekly rates, and, since it is less than week, and javascripts Date.getDay() function works about Monday, you can check if the tracked date's "day" is greater than the end date's "day" (meaning that it would have had to loop around, indicating a weekend)

Phonegap - events such as focus(),blur() not called in JavaScript

I have just started using Phonegap, I wanted to clear the textbox content when the user clicks on the textbox.
HTML:
<input type="text" class="clear" id="dateVal" name="date" value="date" onblur="clear();"/>/
JavaScript
function clear() {
document.getElementsByTagName('input').value = '';
}
But the clear function is not getting called. Also, just tried putting alert in clear()
function(did not help). Everything else working okay. Any help would be appreciated.
Full HTML Code:
<!DOCTYPE html> <html> <head>
<title>Age Calculator</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.1.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
alert('welcome');
}
function calAge() {
var x = confirm('Click here to calculate the age');
if(x == true) {
document.getElementById('ageId').style.display = block';
} else {
navigator.app.exitApp(); }
}
function submitValues() {
var todaysDate = new Date();
var y = todaysDate.getFullYear();
var m = todaysDate.getMonth() + 1;
var d = todaysDate.getDate() + 1;
var myYear = document.getElementById('yearVal').value;
var myMonth = document.getElementById('monthVal').value;
var myDate = document.getElementById('dateVal').value;
var myYear = (y-myYear);
var myMonth = (m-myMonth);
var myDate = (d-myDate);
document.getElementById('ageId').style.display = 'none';
document.getElementById('result').innerHTML = 'You are '+myYear+'years '+myMonth+' months and '+myDate + ' days old :-)';
} function clear() { document.getElementsByTagName('input').value = ''; }
</script> </head> <body>
<button onclick="calAge();">Age Calculator</button> <br>
<div id="ageId" style="display:none;">
<b>Please Enter your Date Of Birth in (dd/mm/yyyy) format:</b>
<input type="text" class="clear" id="dateVal" name="date" value="date" onblur="clear();"/>/
<input type="text" class="clear" id="monthVal" name="month" value="month" />/
<input type="text" class="clear" id="yearVal" name="year" value="year" />
<input type="button" value="submit" onclick = "submitValues();" />
</div>
<div id="result">
</div> </body> </html>
In HTML5 there is a placeholder attribute.
Ex:
<input type="text" placeholder="Enter Date" id="dateVal" name="date" />
We could use this to get what I desired.
Thanks, might be helpful to somebody.

Categories

Resources