Vehicle Rental Rate Calculation - javascript

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)

Related

Countdown timer for every day and hour

I have a difficult task. I need to make a countdown timer that counts every day and every set time for a certain event. First I want to figure out how to make it possible to select specific times for each day (for example the event starts on Monday at 10:30 and have the same event on Monday at 20:00) and how to save them to the databases.
Second I want to figure out how after I write them down so that it shows the earliest time until the next event for each day and so it repeats every week.
Something like this i want - https://i.imgur.com/4kOtMnk.png
<form method="post" action="/adminpanel/event">
#csrf
<div class="card-body">
<div class="form-group">
<label for="FileName">Event Name</label>
<input type="text" class="form-control" id="name" name="event">
</div>
<div class="form-group">
<label for="FileName">Event Name</label>
<select id="select" multiple onchange="showDiv()">
<optgroup label="Weekdays">
<option value="1">Every Day</option>
<option value="2">Monday</option>
</optgroup>
</select>
</div>
<!-- Every Day -->
<div class="form-group" id="hidden_div1" style="display: none;">
<label for="FileName">Every Day</label>
<input type="text" class="form-control" id="name" name="everyday"
placeholder="Event hours in Every Day seperated with comma ( , ) Time format hh:mm (must be sorted by time asc)">
</div>
<!-- Monday -->
<div class="form-group" id="hidden_div2" style="display: none;">
<label for="FileName">Monday</label>
<input type="text" class="form-control" id="name" name="monday"
placeholder="Event hours in Monday seperated with comma ( , ) Time format hh:mm (must be sorted by time asc)">
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary col-12">Submit</button>
</div>
</form>
Countdown HTML
<!-- Countdown -->
<script type="text/javascript">var newdate = 'here i need to put time';</script>
<div class="countdowntitle">
<div id="timer"></div>
</div>
Countdown JS
function updateTimer() {
future = Date.parse(newdate);
now = new Date();
diff = future - now;
days = Math.floor(diff / (1000 * 60 * 60 * 24));
hours = Math.floor(diff / (1000 * 60 * 60));
mins = Math.floor(diff / (1000 * 60));
secs = Math.floor(diff / 1000);
d = days;
h = hours - days * 24;
m = mins - hours * 60;
s = secs - mins * 60;
document.getElementById("timer")
.innerHTML =
'<div>' + d + '<span>Days</span></div>' +
'<div>' + h + '<span>Hours</span></div>' +
'<div>' + m + '<span>Minutes</span></div>' +
'<div>' + s + '<span>Seconds</span></div>';
}
setInterval('updateTimer()', 1000);
And this is Controller
public function do_event(Request $request)
{
$this->validate($request,[
'event'=>'unique:XWEB.XWEB_EVENT,event',
'monday'=>'date_format:H:i',
]);
$insert = DB::connection('XWEB')->table('XWEB_EVENT')
->insert(['event' => $request->event, 'time' => $request->monday]);
return redirect()->back()->withSuccess('You have added this event successfully!');
}

Boostrap datepicker stuck after setStartDate when click on decade or century

i have issue with boostrap datepicker after setting a start date allowed to pick which is when start date allowed is in 07-11-2021, but if a goes to decade view i can't go back to year 2021 or 2022, when i saw in decade years 2020 that supose to show it back years in allowed that decade is being disabled.
It is because the setStartDate is at 2021, so in decade view mode the 2020 is being disabled and can't show allowed year in that decade.
Here the example
let d = new Date('08/11/2021');
$('.datepicker').datepicker({
todayBtn: "linked",
clearBtn: true,
format: 'd MM yyyy'
}).datepicker('setStartDate', d);
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<div class="form-group">
<label for="input" class="form-control-label">Date</label>
<div class="input-group">
<input class="form-control datepicker" placeholder="d M yyyy" type="text" name="waktu_bayar" id="input" data-date-end-date="0d">
<div class="input-group-append">
<span class="input-group-text"><i
class="ni ni-calendar-grid-58 px-1"></i></span>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
For serval hour i'm tyring to digs these bug, look for other people question and so on, and the i'm get an epiphany that i should do something when the datepicker table being show, and the rest add some javascript in that show event.
First we can create a function that can return a value abaut what decade or century from a date, than do some DOM to enableing some decade or a some century.
Even through this is bit messy hire and there but i got the result what i want.
Here The code
let d = new Date('08/11/2021');
// extended function for datepicker
const dateRanges = (date = new Date(), rule = 10, sum = 0) => Math.floor(date.getFullYear() / rule) * rule + sum;
$('.datepicker').datepicker({
todayBtn: "linked",
clearBtn: true,
language: 'id',
format: 'd MM yyyy'
}).change(function(e) {
// submitControl(e.target);
}).on('show', function(e) {
let allowedPicker = [],
untilPicker = undefined,
year = undefined;
if (e.viewMode == 3) {
// Start From This(d) Decade
allowedPicker = [dateRanges(d)];
// Until This(default dateRanges) Decade
untilPicker = dateRanges();
year = 10;
} else if (e.viewMode == 4) {
// daterange second params set to 100 a century
// Start From This(d) Century
allowedPicker = [dateRanges(d, 100)];
// Until This(now) Century
untilPicker = dateRanges(new Date(), 100);
year = 100;
}
if (allowedPicker.length > 0) {
if (allowedPicker.find(element => element == untilPicker) == undefined) {
allowedPicker.push(untilPicker)
}
if (allowedPicker.length > 1 && allowedPicker[1] - allowedPicker[0] > year) {
let loop = 1;
do {
if (allowedPicker.find(element => element == (loop * year)) == undefined) {
allowedPicker.push(allowedPicker[loop - 1] + year);
}
loop++;
} while ((allowedPicker[1] - allowedPicker[0]) / year > loop);
allowedPicker.sort();
}
allowedPicker.forEach(pickElement => {
$('.datepicker.datepicker-dropdown table tbody td>span.disabled:contains(' + pickElement + ')').removeClass('disabled');
});
}
}).datepicker('setStartDate', d);
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet" />
<div class="form-group">
<label for="input" class="form-control-label">Date</label>
<div class="input-group">
<input class="form-control datepicker" placeholder="d M yyyy" type="text" name="waktu_bayar" id="input" data-date-end-date="0d">
<div class="input-group-append">
<span class="input-group-text"><i
class="ni ni-calendar-grid-58 px-1"></i></span>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>

How do I get the number of days from 2 user inputs and then multiply it with another user input which is amount in JavaScript?

I'm trying to create a simple fine calculator, I have two user input dates and a user input amount.
I need to subtract the 2 dates and then multiply the number of days by the fine amount. I went through a bunch of videos about dates, but none of them ever take user input. I am very new to javascript so I don't know why it won't show me my result. Could someone tell me what's wrong with my code?
if (isset($_POST['calcDiff'])) {
$("#bdate").datetimepicker({
timepicker: false,
format: 'y-m-d'
});
$("#rdate").datetimepicker({
timepicker: false,
format: 'y-m-d'
});
function calcDiff() {
var bdate = new Date($("#bdate").val());
var rdate = new Date($("#rdate").val());
var amount = $('#amount').val();
var timeDifference = rdate.getTime() - bdate.getTime();
var milliSecondsInOneSecond = 1000;
var secondInOneHour = 3600;
var hourInOneDay = 24;
var daysDiff = timeDifference / (milliSecondsInOneSecond * secondInOneHour * hourInOneDay);
var fine = daysDiff * amount.val();
alert(fine);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="finecalc" action="" method="post">
<p>
Borrowed date
<input type="date" name="bdate" id="bdate" required="required" value="<?php echo $bdate; ?>" />
</p>
<p>
Return date</b>
<input type="date" name="rdate" id="rdate" required="required" value="<?php echo $rdate; ?>" /> <b>
</p>
<p>Enter fine amount per day</b>
<input type="text" name="amount" size="10"><b>
</p><button onclick="calcDiff()">Calculate Fine</button><p id="display"></p>
</form>
You can get the value from each input, then actually just subtract the dates to get the epoch difference and with that number you can convert it to days and multiply by the fine.
I added a JS that does just that.
function calcDiff(){
const date1 = new Date(document.querySelector('#bdate').value);
const date2 = new Date(document.querySelector('#rdate').value);
const penalty = document.querySelector('input[name="amount"]').value;
const diff_ms = date2 - date1;
// ms -> s -> min -> h -> days
const days = diff_ms / 1000 / 60 / 60 / 24;
const amount_to_pay = days * penalty;
console.log('$' + amount_to_pay);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="finecalc" action="" method="post">
<p>
Borrowed date
<input type="date" name="bdate" id="bdate" required="required" value="<?php echo $bdate; ?>" />
</p>
<p>
Return date</b>
<input type="date" name="rdate" id="rdate" required="required" value="<?php echo $rdate; ?>" /> <b>
</p>
<p>Enter fine amount per day</b>
<input type="text" name="amount" size="10"><b>
</p><button type="button" onclick="calcDiff()">Calculate Fine</button><p id="display"></p>
</form>
var amount = $('#amount').val();
...
var fine = daysDiff * amount.val();
Maybe no need to use amount.val()?
var fine = daysDiff * amount;
Also, remove the comma in this line:
var daysDiff = timeDifference / (, milliSecondsInOneSecond * secondInOneHour * hourInOneDay);
First you need to calculate difference between 2 dates and total number of days
const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); // calculate number of days
console.log(diffDays + " days");
var amount = $('#amount').val(); //store Amount value into amount variable
Then calculate fine:
var fine = daysDiff * amount;
This is what wound up working for me, thank you to all that helped.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="enterbooks.css" />
</head>
<body style="background: url(library.png); background-size: 100%;">
<div class="content">
<h1>Hey admin calulate you fines here!</h1>
<script>
function calcDiff() {
const date1 = new Date(document.querySelector('#bdate').value);
const date2 = new Date(document.querySelector('#rdate').value);
const penalty = document.querySelector('input[name="amount"]').value;
const diff_ms = date2 - date1;
// ms -> s -> min -> h -> days
const days = diff_ms / 1000 / 60 / 60 / 24;
const amount_to_pay = days * penalty;
alert(amount_to_pay);
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="finecalc" action="" method="post">
<p>
Borrowed date
<input type="date" id="bdate" required="required" value="<?php echo $bdate; ?>" />
</p>
<p>
Return date</b>
<input type="date" id="rdate" required="required" value="<?php echo $rdate; ?>" /> <b>
</p>
<p>Enter fine amount per day</b>
<input type="text" name="amount" size="10"><b>
</p><button type="button" onclick="calcDiff()">Calculate Fine</button>
<p id="display"></p>
</form>
</div>
</body>
</html>

why is the required attribute in the form not working

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

Doing math with Time using js

I have the following code:
HTML:
<form onsubmit="return false;">
<div class="col-5">
<label>
Page Time
<input id="pageTime" name="pageTime" type="time" step="1" tabindex="9">
</label>
</div>
<div class="col-5">
<label>
Ack Time
<input id="ackTime" name="ackTime" type="time" step="1" tabindex="10">
</label>
</div>
<div class="col-5">
<label>
Arrival Time
<input id="arrivalTime" name="arrivalTime" type="time" step="1" tabindex="11">
</label>
</div>
<div class="col-5">
<label>
Start Replace / Root Cause Found
<input id="startReplace" name="startReplace" type="time" step="1" tabindex="12">
</label>
</div>
<div class="col-5">
<label>
Replaced / Repair Completed
<input id="replaced" name="replaced" type="time" step="1" tabindex="13">
</label>
</div>
<div class="col-4">
<label>
Engagement
<input type="text" id="engagement" name="engagement" value="" readonly="readonly" />
</label>
</div>
<div class="col-4">
<label>
Arrival
<input type="text" id="arrival" name="arrival" value="" readonly="readonly" />
</label>
</div>
<div class="col-4">
<label>
Investigation
<input type="text" id="investigation" name="investigation" value="" readonly="readonly" />
</label>
</div>
<div class="col-4">
<label>
Mitigate
<input type="text" id="mitigate" name="mitigate" value="" readonly="readonly" />
</label>
</div>
<div class="col-1" style="text-align: center">
<label>
Total Ops Phases
<input type="text" name="totalOpsPhases" id="totalOpsPhases" value="" readonly="readonly" />
</label>
</div>
<div class="col-submit">
<button class="submitbtn" tabindex="14" onclick="opsTime();">Do the Math</button>
</div>
</form>
JS:
function toSeconds(time_str) {
// Extract hours, minutes and seconds
var parts = time_str.split(':');
var sum = 0;
// compute and return total seconds
for (c = 0; c <= 2; c++) {
if (c === 0) {
sum += parts[0] * 3600;
} else if (c === 1) {
sum += parts[1] * 60;
} else if (c === 2) {
if (parts[2] !== 'undefined') {
sum += parts[2];
}
}
}
return sum;
}
function opsTime() {
var time = [document.getElementById('pageTime').value, document.getElementById('ackTime').value, document.getElementById('arrivalTime').value, document.getElementById('startReplace').value, document.getElementById('replaced').value];
// Created an array to easily do the math :)
// Array mapping:
// 0 = pageTime
// 1 = ackTime
// 2 = arrivalTime
// 3 = startReplaceTime
// 4 = replacedTime
for (i = 0; i <= 4; i++) {
if (i === 4) {
var start = time[0];
var end = time[4];
} else {
start = time[i];
end = time[i + 1];
}
var startSec = toSeconds(start);
var endSec = toSeconds(end);
var difference = Math.abs(endSec - startSec);
// format time differnece
var result = [
Math.floor(difference / 3600), // an hour has 3600 seconds
Math.floor((difference % 3600) / 60), // a minute has 60 seconds
difference % 60
];
// 0 padding and concatation
result = result.map(function (v) {
return v < 10 ? '0' + v : v;
}).join(':');
var res = [];
res[i] = result;
}
document.getElementById('engagement').value = res[0];
document.getElementById('arrival').value = res[1];
document.getElementById('investigation').value = res[2];
document.getElementById('mitigate').value = res[3];
document.getElementById('totalOpsPhase').value = res[4];
}
What I'm trying to do is to pick the times filled in the inputs and show the difference in the inputs boxes below.
Engagement should be the time difference between Page Time and Ack Time;
Arrival should be the time difference between Ack Time and Arrival Time;
Investigation should be the time difference between Arrival and Start Replace Time;
Mitigate should be the time difference between Start Replace and Replaced time;
Total Ops Phases should be the time difference between Replaced and Page time.
I'm stuck on the code above for almost 8 hours, changed a lot of things trying to do the math and put each time difference inside an array and then use it to fill the inputs, but it seems the array isn't get filled with data.
Unfortunately I have to use the seconds as well, and I couldn't find much material with different solutions to calculate the difference of times using it.
I will be glad if someone can see another way to solve this matter.
Thanks in advance!
PS: Tried to insert a print of the form but I don't have the reputation needed.
The type="time" attribute is only supported by chrome, not Firefox or Internet Explorer so you should be using a compatibility library like these or one of your own making. If you just want to use chrome you can use valueAsNumber:
v.valueAsNumber
56013000
v.valueAsDate
Thu Jan 01 1970 10:33:33 GMT-0500 (EST)
v.value
"15:33:33"
Note that the Chrome console will show you these options with auto suggest.
Also jsfiddle

Categories

Resources