Boostrap datepicker stuck after setStartDate when click on decade or century - javascript

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>

Related

Comparing two custom format dates jquery

I have tried to validate my dates if start date is less than end date it should alert but it only work with in same month, but when i compare dates of one month date to another month date it keeps stops me select less date even it is already.
here is what i have done so far,
$('#datepicker2').change(function () {
var startDate = new Date($('#datepicker').val());
var endDate = new Date($('#datepicker2').val());
if (startDate < endDate){
alert("selected date is above pickup date, ");
}
});
here is my html
<div class="col-md-4">
<div class="row">
<div class="col-md-6">
<input type="text" id="datepicker" required name="pickupDate" placeholder="Pickup Date">
</div>
<div class="col-md-6">
<input class="" id="datetimepicker4" autocomplete="off" required name="pickupTime" placeholder="Pickup Time">
</div>
</div>
</div>
<div class="col-md-4">
<div class="row ct-date-row">
<div class="col-md-6">
<input type="text" id="datepicker2" required name="dropDate" placeholder="Drop off Date">
</div>
<div class="col-md-6">
<input class="" autocomplete="off" id="datetimepicker5" required name="dropTime" placeholder="Drop Time">
</div>
</div>
</div>
my date format is d/m/y if this is making issue then how could i possibly define formate within new date and compare them. Thanks
I want when same date it hides previous time on time drop down of jquery.
$('#datetimepicker5').timepicker({
timeFormat: 'HH:mm',
});
$('#datetimepicker4').timepicker({
timeFormat: 'HH:mm',
});
format of my time i am not being to get time which is selected,
jQuery('document').ready(function(){
jQuery('#datetimepicker5').on('change paste keyup', function() {
var x = jQuery("#datetimepicker5").val();
alert(x);
});
});
So, you are using jQuery Ui DatePicker, there is native way to get date with getDate, here you go:
For compare your dates if equal or same you need to use Date.parse() , you need to do this:
if (Date.parse(startDate) === Date.parse(endDate))
$(function() {
$("#datepicker").datepicker({
dateFormat: "d/m/y"
});
$("#datepicker2").datepicker({
dateFormat: "d/m/y"
});
$('#datetimepicker5').timepicker({
timeFormat: 'HH:mm',
});
$('#datetimepicker4').timepicker({
timeFormat: 'HH:mm',
});
});
$('#datepicker2').on('paste keyup change', function() {
var startDate = $('#datepicker').datepicker("getDate");
var endDate = $('#datepicker2').datepicker("getDate");
if (startDate > endDate) {
alert("selected date is above pickup date, ");
} else if (Date.parse(startDate) === Date.parse(endDate)) {
alert("same");
var dt = new Date();
var phours = dt.getHours() + 3;
var time = phours + ":" + "00";
alert(time);
jQuery('#datetimepicker5').timepicker({
minTime: time
});
jQuery('#datetimepicker4').timepicker({
minTime: time
});
$('#datetimepicker4').val(time)
$('#datetimepicker5').val(time)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://www.jonthornton.com/jquery-timepicker/jquery.timepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha256-KM512VNnjElC30ehFwehXjx1YCHPiQkOPmqnrWtpccM=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha256-rByPlHULObEjJ6XQxW/flG2r+22R5dKiAoef+aXWfik=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.10.0/jquery.timepicker.min.css" integrity="sha256-zV9aQFg2u+n7xs0FTQEhY0zGHSFlwgIu7pivQiwJ38E=" crossorigin="anonymous" />
<div class="col-md-4">
<div class="row">
<div class="col-md-6">
<input type="text" id="datepicker" required name="pickupDate" placeholder="Pickup Date">
</div>
<div class="col-md-6">
<input class="" id="datetimepicker4" autocomplete="off" required name="pickupTime" placeholder="Pickup Time">
</div>
</div>
</div>
<div class="col-md-4">
<div class="row ct-date-row">
<div class="col-md-6">
<input type="text" id="datepicker2" required name="dropDate" placeholder="Drop off Date">
</div>
<div class="col-md-6">
<input class="" autocomplete="off" id="datetimepicker5" required name="dropTime" placeholder="Drop Time">
</div>
</div>
</div>
You can convert your both dates to seconds and then compare it. then it will work like charm:
i.e.
var date1 = new Date("2015-08-25T15:35:58.000Z");
var seconds1 = date1.getTime() / 1000; //1440516958
Use Date.parse()
The Date.parse() method parses a string representation of a date and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
$('#datepicker2').change(function () {
var startDate = new Date($('#datepicker').val());
var endDate = new Date($('#datepicker2').val());
if (Date.parse(startDate) < Date.parse(endDate)){
alert("selected date is above pickup date, ");
}
});

Hover effect in between the selected start date and end date in css

I am working on a website in which I want the hover effect to be place (as shown below in an image) in between the selected (Suppose July 26th) start date and the dates which we will select on the end date:
The HTML and JS/JQuery code which I have used are as follows:
HTML:
<div class="dates">
<div class="start_date" style="width:50%;margin-right:3%;">
<input readonly="readonly" class="form-control start_date mb-4" type="text" placeholder="start date" id="startdate_datepicker">
</div>
<div class="end_date" style="width:50%;margin-left:3%;">
<input readonly="readonly" class="form-control end_date mb-4" type="text" placeholder="end date" id="enddate_datepicker">
</div>
</div>
JS/JQuery code:
let startDateUI = $("#startdate_datepicker").datepicker({
numberOfMonths:[1, 2],
todayHighlight: true,
beforeShowDay: function (calDate) {
return calDate - new Date() < 0 ? [false, '', ''] : [true, '','']
}
});
$("#enddate_datepicker").datepicker({
numberOfMonths:[1, 2],
todayHighlight: true,
beforeShowDay: function (calDate) {
let selectedStartDate = $( "#startdate_datepicker" ).datepicker( "getDate" )
return calDate - selectedStartDate < 0 ? [false, 'disable-day', 'not available day!!!'] : [true, '','']
}
});
Problem Statement:
I am wondering what code I need to add in the CSS so that hover comes in effect in between the selected start date and the end date which the users will select from the end date section similar to airbnb website.
Below is one simple demo for highlight days between start date and hover date.
The steps:
remove class=highlight-day from all .ui-datepicker-calendar tr td.highlight-day
find out all .ui-datepicker-calendar tr td then loop&add css class=highlight-day until reach the hover date.
uses css selector .highlight-day a:not(.disable-day) to highlight the days.
let startDateUI = $("#startdate_datepicker").datepicker({
numberOfMonths:[1, 2],
todayHighlight: true,
beforeShowDay: function (calDate) {
return calDate - new Date() < 0 ? [false, '', ''] : [true, '','']
}
});
$("#enddate_datepicker").datepicker({
numberOfMonths:[1, 2],
todayHighlight: true,
beforeShowDay: function (calDate) {
let selectedStartDate = $( "#startdate_datepicker" ).datepicker( "getDate" )
return calDate - selectedStartDate < 0 ? [false, 'disable-day', 'not available day!!!'] : [true, '','']
}
});
$("#enddate_datepicker").datepicker('widget').on('mouseover', 'tr td', function () {
if(!$( "#startdate_datepicker" ).datepicker( "getDate" )){
return
}//this is hard code for start date
let calendarId = $(this).closest('.ui-datepicker').attr('id')
// clear up highlight-day class
$('#' + calendarId + ' .ui-datepicker-calendar tr td.highlight-day').each((index, item) => {
$(item).removeClass('highlight-day')
})
// loop& add highligh-day class until reach $(this)
let tds = $('#' + calendarId + ' .ui-datepicker-calendar tr td')
for(let index = 0; index < tds.size(); ++index) {
let item = tds[index]
$(item).addClass('highlight-day')
if($(item)[0].outerHTML === $(this)[0].outerHTML) {
break
}
}
})
.disable-day{
color: gray;
}
.highlight-day a:not(.disable-day) {
background-color: blue;
}
<link href="https://cdn.bootcss.com/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="dates">
<div class="start_date" style="width:50%;margin-right:3%;">
<input readonly="readonly" class="form-control start_date mb-4" type="text" placeholder="start date" id="startdate_datepicker">
</div>
<div class="end_date" style="width:50%;margin-left:3%;">
<input readonly="readonly" class="form-control end_date mb-4" type="text" placeholder="end date" id="enddate_datepicker">
</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)

Start date End date validation in angularjs submit form should be disabled

I dont wana submit my form if Start date-End date validation fails...In my form if i have this...
<form name="scheduleForm" id="scheduleForm" class="form-vertical" novalidate>
<input type="text" placeholder="Start Date" ng-model="schedule.startDate" class="form-control" ui-date novalidate required>
<input type="text" name="endDate" placeholder="End Date" ng-model="schedule.endDate" class="form-control" ui-date novalidate ng-change='checkErr(schedule.startDate,schedule.endDate)' required>
<button class="btn btn-primary" ng-click="addSchedule(schedule)" ng-disabled="errMessage || scheduleForm.$invalid">Add Schedule</button>
And in the controller :
$scope.checkErr = function(startDate,endDate) {
$scope.errMessage = '';
var curDate = new Date();
if(new Date(startDate) > new Date(endDate)){
$scope.errMessage = 'End Date should be greater than start date';
// var err=function() {
// $window.alert('End Date should be greater than start date');};
// err();
return false;
}
if(new Date(startDate) < curDate){
$scope.errMessage = 'Start date should not be before today.';
// var err=function() {
// $window.alert('Start date should not be before today.');};
// err();
return false;
}
};
and in add function:
$scope.addSchedule=function(schedule){
$scope.schedules.push({
startDate: schedule.startDate,
endDate: schedule.endDate,
});
schedule.startDate='';
schedule.endDate='';
};
prob is button looks disable bt its allowing data to be added... do help thank in advance
to compare time properly should use getTime() function
if(new Date(startDate).getTime() > new Date(endDate).getTime())
and check date validation in button so no need to use checkErr() on end date change
<button class="btn btn-primary" ng-click="addSchedule(schedule)" ng-disabled="checkErr(schedule.startDate,schedule.endDate)|| scheduleForm.$invalid">Add Schedule</button>
and your checkErr function like:
$scope.checkErr = function(startDate,endDate) {
var curDate = new Date();
// can set error message if need to show
if(new Date(startDate).getTime() > new Date(endDate).getTime()){
return true; // if invalid
}
if(new Date(startDate).getTime() < curDate.getTime()){
return true; // if invalid
} else {
return false // if valid
}
};
Why not you add validation when elements are ready. Look at the demo here https://plnkr.co/edit/JunWzLjhLCPMqZnxsSYw?p=preview
var app = angular.module('myApp', ['ui.date']);
app.controller('MainCtrl', function($scope) {
$scope.schedule = {};
$scope.dateOptions = {
changeYear: true,
date:$scope.schedule.startDate,
changeMonth: true,
yearRange: '1900:-0',
maxDate: new Date(new Date().setDate(new Date().getDate() + 2)),
minDate:new Date()
};
$scope.addSchedule=function(schedule){
console.log($scope.schedule)
};
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="date.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<form name="scheduleForm" id="scheduleForm" class="form-vertical" novalidate>
<input type="text" placeholder="Start Date" ng-model="schedule.startDate" ui-date-format="DD, d MM, yy"
class="form-control" min-date="minDate" max-date="maxDate" ui-date="dateOptions" novalidate required>
<!--<input type="text" name="endDate" placeholder="End Date" ui-date-format="DD, d MM, yy" ng-model="schedule.endDate" class="form-control" ui-date novalidate ng-change='checkErr(schedule.startDate,schedule.endDate)' required>
-->
<button class="btn btn-primary" ng-click="addSchedule(schedule)" ng-disabled="scheduleForm.$invalid">Add Schedule</button>
</form>
</body>
</html>

Datetimepicker bootstrap not working proberly in asp.net website

I could use some eyes to check what i have done wrong with this code. I have tried to follow an example where i have made to input boxes for check-in and check-out.
It look like this:
Check-in
Input box (datetimepicker1)
Check-out
Input box (datetimepicker2)
I'm trying to make it so when you pick a date in datepicker1, you can pick an earlier date with the datetimepicker2 form. You have to pick a day at least 1 day ahead.
My asp code:
<div class="form-group">
<div class="input-append date form_datetime">
<asp:Label ID="Label1" runat="server" Text="Check-in Date:"></asp:Label>
<input type="text" class="form-control" id="datetimepicker1" />
</div>
</div>
<div class="form-group">
<div class="input-append date form_datetime">
<asp:Label ID="Label2" runat="server" Text="Check-out Date:"></asp:Label>
<input type="text" class="form-control" id="datetimepicker2" />
</div>
</div>
Javascript:
<script type="text/javascript">
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#datetimepicker1').datepicker({
onRender: function (date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 1);
checkout.setValue(newDate);
}
checkin.hide();
$('#datetimepicker2')[0].focus();
}).data('datepicker');
var checkout = $('#datetimepicker2').datepicker({
onRender: function (date) {
return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
checkout.hide();
}).data('datepicker');
</script>
I'm sure that i got the right js files in, because it have worked with some other code before, but it was not that smart, because i don't want any icons, it should only be a text box, and when u click on it, the datetimepicker should open it self.
Hope someone can see what is wrong with this.

Categories

Resources