How to reset jquery datepicker onkeyup? - javascript

My jquery date pickers work exactly as they should, however my issue is that if one of the datepickers is removed from the textbox then the value in the date calculated box (CalcDate1) should disappear. My code is as follows
<script type="text/javascript">
$(function () {
$('#datepicker7').datepicker({
showOnFocus: false,
showTrigger: '#calImg',
beforeShowDay: $.datepicker.noWeekends,
pickerClass: 'noPrevNext',
dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true,
onClose: function (selectedDate) { $("#datepicker8").datepicker("option", "minDate", selectedDate) },
onSelect: function (dateStr) {
var min = $(this).datepicker('getDate');
$('#datepicker8').datepicker('option', "calculateWeek", min);
datepicked();
}
});
$('#datepicker8').datepicker({
showOnFocus: false,
showTrigger: '#calImg',
beforeShowDay: $.datepicker.noWeekends,
pickerClass: 'noPrevNext',
dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true,
onSelect: function (dateStr) {
var max = $(this).datepicker('getDate');
$('#datepicker7').datepicker('option', "calculateWeek", max);
datepicked();
}
});
});
var datepicked = function () {
var from = $('#datepicker7');
var to = $('#datepicker8');
var nights = $('#CalcDate1');
var startDate = from.datepicker('getDate');
startDate.setDate(startDate.getDate() + 1);
var endDate = to.datepicker('getDate')
// Validate input
if (endDate && startDate) {
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
var days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1)
var days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
var days = days - 1
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
var days = days - 1
nights.val(days);
}
}
</script>
I added the following two pieces of code to the their relative datepickers but they didn't work
keyup(function(e) {
if(e.keyCode == 8 || e.keyCode == 46) {
$.datepicker._clearDate(this);
$( "#datepicker8" ).datepicker( "option", "minDate", "today" );
}
});
keyup(function(e) {
if(e.keyCode == 8 || e.keyCode == 46) {
$.datepicker._clearDate(this);
$( "#datepicker7" ).datepicker( "option", "maxDate", "" );
}
});
My html helpers are
<div class="form-group">
#Html.LabelFor(model => model.DateToAdvisors, "Date To Advisors", new { #class = "control-label col-md-5" })
<div class="col-md-offset-0">
#Html.TextBoxFor(model => model.DateToAdvisors, new { #class = "datepicker7", id = "datepicker7" })
#Html.ValidationMessageFor(model => model.DateToAdvisors)
</div>
</div>
<div class="form-group" style="padding-top:75px">
#Html.LabelFor(model => model.ReplyFormAdvisors, "Reply From Advisors", new { #class = "control-label col-md-5" })
<div class="col-md-offset-0">
#Html.TextBoxFor(model => model.ReplyFormAdvisors, new { #class = "datepicker8", id = "datepicker8" })
#Html.ValidationMessageFor(model => model.ReplyFormAdvisors)
</div>
</div>
<div class="form-group" style="padding-top:175px">
#Html.LabelFor(model => model.CalcDate1, "Date Calculated", new { #class = "control-label col-md-5" })
<div class="col-md-offset-0">
#Html.TextBoxFor(model => model.CalcDate1)
#Html.ValidationMessageFor(model => model.CalcDate1)
</div>
</div>

Related

Textbox onChange event and Datepicker onSelect conflict

I have two text boxes for date fields. User is allowed to enter date in those fields via both jQuery-ui Datepicker and via manually typing through keyboard. The requirement is after entering date in the 1st textbox, the second textbox should get populated with the date exactly 1 year later.I have handled most of the scenarios.
I will try to explain clearly in which scenario I am facing the issue. Suppose I am typing in the date manually from keyboard and suddenly I decide to select a different date from Datepicker instead. In this case the the textbox is not showing the selected date from datepicker. I hope I am able to articulate clearly. My guess is Datepicker's onSelect() event is not getting fired in this particular scenario because of any conflict with the textbox's onChange() event.
$('#datepicker1').datepicker({
constrainInput: "true",
dateFormat: "mm/dd/yy",
changeMonth: true,
changeYear: true,
onSelect: function (date) {
var parsedDate = parseDate(date);
var moddate = new Date(Date.parse(parsedDate));
moddate.setFullYear(moddate.getFullYear() + 1);
var newDate = moddate.toDateString();
newDate = new Date(Date.parse(newDate));
$("#datepicker2").datepicker("option", "maxDate", newDate);
$('#datepicker2').datepicker('setDate', newDate);
}
});
$('#datepicker2').datepicker({
dateFormat: "mm/dd/yy",
changeMonth: true,
changeYear: true,
});
var maskConfig = {
leapday: "29-02-",
separator: "/",
showMaskOnHover: false,
showMaskOnFocus: false,
placeholder: "00/00/0000"
}
$('#datepicker1').inputmask('mm/dd/yyyy', maskConfig);
$('#datepicker2').inputmask('mm/dd/yyyy', maskConfig);
$('#datepicker1').on("change",function () {
var parsedDate = parseDate($('#datepicker1').val());
var date = new Date(Date.parse(parsedDate));
date.setFullYear(date.getFullYear() + 1);
var newDate = date.toDateString();
newDate = new Date(Date.parse(newDate));
$("#datepicker2").datepicker("option", "maxDate", newDate);
$('#datepicker2').datepicker('setDate', newDate);
});
function parseDate(input) {
var parts = input.split('/');
return new Date(parts[2], parts[0] - 1, parts[1]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>
<input type="text" id="datepicker1"/>
<input type="text" id="datepicker2"/>
I couldn't find any exact fix for this issue. I am currently going with a small hack/workaround. I am hiding the datepicker as soon as user starts typing inside the textbox. I am using the "keyup" event handler.
$('#datepicker1').datepicker({
constrainInput: "true",
dateFormat: "mm/dd/yy",
changeMonth: true,
changeYear: true,
onSelect: function (date) {
var parsedDate = parseDate(date);
var moddate = new Date(Date.parse(parsedDate));
moddate.setFullYear(moddate.getFullYear() + 1);
var newDate = moddate.toDateString();
newDate = new Date(Date.parse(newDate));
$("#datepicker2").datepicker("option", "maxDate", newDate);
$('#datepicker2').datepicker('setDate', newDate);
}
});
$('#datepicker2').datepicker({
dateFormat: "mm/dd/yy",
changeMonth: true,
changeYear: true,
});
var maskConfig = {
leapday: "29-02-",
separator: "/",
showMaskOnHover: false,
showMaskOnFocus: false,
placeholder: "00/00/0000"
}
$('#datepicker1').inputmask('mm/dd/yyyy', maskConfig);
$('#datepicker2').inputmask('mm/dd/yyyy', maskConfig);
$('#datepicker1').on("change",function () {
var parsedDate = parseDate($('#datepicker1').val());
var date = new Date(Date.parse(parsedDate));
date.setFullYear(date.getFullYear() + 1);
var newDate = date.toDateString();
newDate = new Date(Date.parse(newDate));
$("#datepicker2").datepicker("option", "maxDate", newDate);
$('#datepicker2').datepicker('setDate', newDate);
});
$('#datepicker1').on('keyup', function() {
if (this.value.length > 0) {
$('#datepicker1').datepicker('hide') ;
}
else{
$('#datepicker1').datepicker('show') ;
}
});
$('#datepicker2').on('keyup', function() {
if (this.value.length > 0) {
$('#datepicker2').datepicker('hide') ;
}
else{
$('#datepicker2').datepicker('show') ;
}
});
function parseDate(input) {
var parts = input.split('/');
return new Date(parts[2], parts[0] - 1, parts[1]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>
<input type="text" id="datepicker1"/>
<input type="text" id="datepicker2"/>

Set the min date of the other datepicker 1 day ahead of my first datepicker

I'm using Materializecss. Now I'm creating a hotel reservation system. What I want is, when I select a date on my DateIn Datepicker, the DateOut Datepicker min date should be 1 day ahead of the date selected. At first selection it is working. But when I try to select a date of check in higher than the selected date out, the min date for dateout picker wont change.
$('#dp_ci').pickadate(
{
selectMonths: true, // Creates a dropdown to control month
min : new Date(),
clear: 'Clear',
close: 'Ok',
closeOnSelect: false // Close upon selecting a date,
});
$('#dp_ci').change(function(){
selected_ci_date ="";
selected_ci_date = $('#dp_ci').val();
if (selected_ci_date != null)
{
var cidate = new Date(selected_ci_date);
alert(cidate);
$("#dp_co").val("");
$("#dp_co").removeAttr("disabled");
min_codate = "";
min_codate = new Date();
min_codate.setDate(cidate.getDate()+1);
$('#dp_co').pickadate(
{
min : min_codate,
selectMonths: true, // Creates a dropdown to control month
clear: 'Clear',
close: 'Ok',
closeOnSelect: false // Close upon selecting a date,
});
$('#dp_co').change(function(){
if ($('#dp_co').val() != null)
{
var ci = new Date($('#dp_ci').val());
var co = new Date($('#dp_co').val());
var noOfdays = co.getDate() - ci.getDate() ;
alert(noOfdays);
}
});
}
})
EDIT:
Example:
1st Select:
dp_ci: September 27, 2017 (selected)
dp_co(min): September 28, 2017 (the dates behind are disabled)
dp_co: September 28, 2017 (selected)
2nd Select:(I will select on dp_ci again)
dp_ci: September 29, 2017 (selected)
dp_co(min): September 28, 2017 (still which was supposed to be September 29)
UPDATE: I found an answer that was able to solve my problem. One only thing is the min date of the dp_co shouldn't allow same date with dp_ci: any solutions?
$('#dp_ci').pickadate(
{
selectMonths: true, // Creates a dropdown to control month
today: 'Today',
clear: 'Clear',
close: 'Ok',
min: new Date()
});
var from_$input = $('#dp_ci').pickadate(),
from_picker = from_$input.pickadate('picker')
var to_$input = $('#dp_co').pickadate(),
to_picker = to_$input.pickadate('picker')
// Check if there’s a “from” or “to” date to start with.
if ( from_picker.get('value') )
{
to_picker.set('min', from_picker.get('select'))
}
if ( to_picker.get('value') )
{
from_picker.set('max', to_picker.get('select'))
}
// When something is selected, update the “from” and “to” limits.
from_picker.on('set', function(event)
{
if ( event.select )
{
to_picker.set('min', from_picker.get('select'))
}
else if ( 'clear' in event )
{
to_picker.set('min', false)
}
})
to_picker.on('set', function(event)
{
if ( event.select )
{
from_picker.set('max', to_picker.get('select'))
}
else if ( 'clear' in event )
{
from_picker.set('max', false)
}
})
Got the code here:CodePen
You need to save the picker object on both the start-picker and end-picker, and when the startpicker change - you only need to set the min value of the end picker:
var startdate = $('#dp_ci').pickadate('picker');
var enddate = $('#dp_co').pickadate('picker');
$('#dp_ci').change(function() {
if (selected_ci_date != null) {
enddate.set('min', min_codate);
}
})
Here is the complete example:
$('#dp_ci').pickadate({
selectMonths: true, // Creates a dropdown to control month
min : new Date(),
clear: 'Clear',
close: 'Ok',
closeOnSelect: false // Close upon selecting a date,
})
var startdate = $('#dp_ci').pickadate('picker');
$('#dp_co').pickadate({
min : new Date(),
selectMonths: true, // Creates a dropdown to control month
clear: 'Clear',
close: 'Ok',
closeOnSelect: false // Close upon selecting a date,
})
var enddate = $('#dp_co').pickadate('picker');
$('#dp_ci').change(function() {
selected_ci_date ="";
selected_ci_date = $('#dp_ci').val();
if (selected_ci_date != null) {
var cidate = new Date(selected_ci_date);
alert(cidate);
$("#dp_co").val("");
$("#dp_co").removeAttr("disabled");
min_codate = "";
min_codate = new Date();
min_codate.setDate(cidate.getDate()+1);
enddate.set('min', min_codate);
}
})
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<div class = "row">
<div class ="col s6">
<label>Date of Check-in </label>
<input type="text" class="datepicker" id="dp_ci">
</div>
<div class ="col s6">
<label>Date of Check-out </label>
<input disabled="true" type="text" class=" datepicker" id="dp_co">
</div>
</div>
$('#txt_performanceDayFlex1').daterangepicker({
"locale": {
"format": "MM/DD/YY"
},
singleDatePicker: true,
minDate: new Date()
}, function (start, end, label) {
$scope.PerformanceStartDate = start.format('MM/DD/YY');
$scope.minimumDate = minimumFormatRequestDate( $scope.PerformanceStartDate);
LodaDate(); //You need to reload the End Date then it Behave Properly and you can add one day head in $scope.minimumDate this in same format
ResetDateAndtime(1);
$scope.$apply();
});
function LodaDate() {
$('#txt_performanceDayFlex2').daterangepicker({
"locale": {
"format": "MM/DD/YY"
},
singleDatePicker: true,
minDate: $scope.minimumDate,
endDate: new Date()
}, function (start, end, label) {
$scope.PerformanceEndDate = start.format('MM/DD/YY');
$scope.$apply();
});
function minimumFormatRequestDate(date) {
if (date != undefined && date != null) {
var newDate = date.split('.').reverse().join('/')
var d = new Date(newDate),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [day, month, year].join('-');
} else {
return 'NA';
}
}

Specific days for datepicker with json?

I have a booking form with specific days and I colored my specific days if you click on my datepicker you will see
so my quesiton is I use array list for my specific
var firstDate = ['2017-06-15'];
var lastDate = ['2017-12-20'];
var availabledays = ['2017-06-15', '2017-06-16', '2017-06-23', '2017-06-30', ];
var booked = ['2017-06-16', '2017-06-23', '2017-06-24', '2017-06-25'];
var ssdays = [];
but I have to use json that's why I created a json file as below
dates.json
{
"firstDate": [
{ "field": "2017-06-15"}
],
"lasDate":[
{"field":"2017-12-20"}
],
"availabledays":[
{"field":"2017-06-15"},
{"field":"2017-06-16"},
{"field":"2017-06-23"},
{"field":"2017-06-30"}
],
"booked":[
{"field":"2017-06-16"},
{"field":"2017-06-23"},
{"field":"2017-06-24"},
{"field":"2017-06-25"}
]
}
and my question is how to request from server mys json files and then put into datepicker when focus?
and this is my datepicker example full demo
$(function() {
var firstDate = ['2017-06-15'];
var lastDate = ['2017-12-20'];
var availabledays = ['2017-06-15','2017-06-16','2017-06-23','2017-06-30',];
var booked = ['2017-06-16','2017-06-23','2017-06-24','2017-06-25'];
var ssdays = [];
var dateFormat = "mm/dd/yy",
from = $("#checkin").datepicker({
changeMonth : true,
numberOfMonths: 2,
firstDay:1,
minDate:new Date(firstDate),
maxDate:new Date(lastDate),
onSelect: function( selectedDate ) {
var newdate = new Date();
var date = $(this).datepicker('getDate');
date.setTime(date.getTime() + (1000*60*60*24))
$( "#checkout" ).datepicker( "option", "minDate",date );
},
beforeShowDay : function(date){
var y = date.getFullYear().toString(); // get full year
var m = (date.getMonth() + 1).toString(); // get month.
var d = date.getDate().toString(); // get Day
if(m.length == 1){ m = '0' + m; } // append zero(0) if single digit
if(d.length == 1){ d = '0' + d; } // append zero(0) if single digit
var currDate = y+'-'+m+'-'+d;
if(jQuery.inArray(currDate,availabledays) >= 0){
return [false, "ui-highlight"];
}
if(jQuery.inArray(currDate,booked) >= 0){
return [true, "ui-bos"];
}else{
return [true];
}
},
isTo1: true,
}).on("change", function() {
to.datepicker("option", "minDate", getDate(this));
}),
to = $("#checkout").datepicker({
changeMonth : true,
changeYear : true,
firstDay:1,
numberOfMonths: 2,
minDate:new Date(firstDate),
maxDate:new Date(lastDate),
onSelect: function( selectedDate ) {
$( "#checkin" ).datepicker( "option", "maxDate", selectedDate );
},
beforeShowDay : function(date){
var y = date.getFullYear().toString(); // get full year
var m = (date.getMonth() + 1).toString(); // get month.
var d = date.getDate().toString(); // get Day
if(m.length == 1){ m = '0' + m; } // append zero(0) if single digit
if(d.length == 1){ d = '0' + d; } // append zero(0) if single digit
var currDate = y+'-'+m+'-'+d;
if(jQuery.inArray(currDate,booked) >= 0){
return [true, "ui-highlight-donus"];
}
if(jQuery.inArray(currDate,availabledays) >= 0){
return [true, "ui-bos"];
}
if(jQuery.inArray(currDate,ssdays) >= 0){
return [true, "ui-ss-donus"];
}else{
return [true];
}
}
}).on("change", function() {
from.datepicker("option", "maxDate", getDate(this));
});
});
.form{
width:960px;
margin:120px auto;
}
.form input{
width:250px;
padding:10px;
}
.ui-highlight .ui-state-default{background: red !important;border-color: red !important;color: white !important; cursor:no-drop;}
.ui-bos .ui-state-default{background: green !important;border-color: green !important;color: white !important;}
.ui-ss .ui-state-default{background: yellow !important;border-color: yellow !important;color: gray !important; cursor:help;}
.ui-ss-donus .ui-state-default{background: yellow !important;border-color: yellow !important;color: gray !important; cursor:help;}
.ui-highlight-donus .ui-state-default{background: red !important;border-color: red !important;color: white !important; }
.ui-testtarih .ui-state-default{
background:black !important;
color:#FFF !important;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<div class="form">
<input type="text" id="checkin" />
<input type="text" id="checkout" />
<input type="submit" value="Search" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
I would disable the datepicker and grey them out while the request is happening and enable them after the request completed. The jquery ui datepicker can be disabled with $('#checkout').datepicker('disable').
As far as the data format, you can write a couple functions to pull that data out in a success callback. Something like
$.ajax({
url: "your-data-url.com"
})
.done(function(serverFormattedDays) {
var availableDays = serverFormattedDays.map(function(day) {
return day.field;
}
// code to create/edit/modify datepickers here.
};
will return the available days in the format you want.

jQuery Calender UI datepicker doesn't work when we click ESC key, calendar not working after 1st click on IE and Safari

When I click first on JQuery calendar it will display the calendar and if i select date it works smoothly. But When I press the Esc after displaying calendar instead of selecting date, it disappears but I cant get click next time onward.
It works fine in Chrome and Firefox but IE and Safari I cant click second time if i click on ESC after click on first time.
Is there anyone faced this problem? or any solution can suggest for this.
I am using jquery-ui-calendar as below details.
/*! jQuery UI - v1.11.4 - 2016-06-30
* http://jqueryui.com
* Includes: core.js, datepicker.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
Below is my JS code:
/* This Section Custom Calendar*/
$(document).ready(function() {
// jquery date picker
$(function () {
if ($(window).width() < 768) {
$.datepicker.setDefaults({
changeMonth: false,
changeYear: false,
dateFormat: customFormat(),
defaultDate: +0,
minDate: 0,
maxDate: '+364d',
numberOfMonths: 1,
showAnim: 'fadeIn',
showButtonPanel: true
});
}
else {
// Set default datepicker options
$.datepicker.setDefaults({
changeMonth: false,
changeYear: false,
dateFormat: customFormat(),
defaultDate: +0,
minDate: 2,
maxDate: '+364d',
numberOfMonths: 2,
showAnim: 'fadeIn',
showButtonPanel: true
});
}
// Calendar 1
$(function () {
$(function () {
$('#arrivaldate').datepicker({
onSelect: function (dateText, instance) {
var arrivaldateold = CleanDate($("#arrivaldate").val());
var arrdatenew = $.datepicker.parseDate(customFormat(), arrivaldateold);
var arrday = arrdatenew.getDate();
var arrmon = (arrdatenew.getMonth() + 1);
var arrYear = arrdatenew.getFullYear()
if (arrday.toString().length==1){arrday="0"+arrday;}
if (arrmon.toString().length==1){arrmon="0"+arrmon;}
var arrivaldatenew = arrday + "/" + arrmon + "/" + arrYear;
$("#calendararr").val(arrivaldatenew);
// Populate checkout date field
var nextDayDate = $('#arrivaldate').datepicker('getDate', '+3d');
nextDayDate.setDate(nextDayDate.getDate() + 1);
$("#arrivaldate").val(FormatDate(arrivaldatenew));
$('#depaturedate').datepicker('setDate',nextDayDate );
$("#depaturedate").val(ChangeDateFormat(nextDayDate));
},
onClose: function () {
$("#depaturedate").datepicker("show");
}
});
});
// Set checkout datepicker options
$(function () {
$('#depaturedate').datepicker({
// Prevent selecting checkout date before arrival:
beforeShow: customRange
});
});
function customRange(a) {
var deptdateold = CleanDate($("#depaturedate").val());
var deptdatenew = $.datepicker.parseDate(customFormat(), deptdateold);
var dptday = deptdatenew.getDate();
var dptmon = (deptdatenew.getMonth() + 1);
var dptYear = deptdatenew.getFullYear()
if (dptday.toString().length==1){dptday="0"+dptday;}
if (dptmon.toString().length==1){dptmon="0"+dptmon;}
var departuredatenew = dptday + "/" + dptmon + "/" + dptYear;
$("#calendardept").val(departuredatenew);
// changes done by parul starts for 30 days limit
var SelectedDate = CleanDate($("#arrivaldate").val());
var date1 = $.datepicker.parseDate(customFormat(), SelectedDate);
var d = new Date();
var diff = date1 - d;
diff = (diff / (1000 * 3600 * 24));
var maxdiff = parseInt(diff);
maxdiff = maxdiff + 31;
var b = new Date();
var c = new Date(b.getFullYear(), b.getMonth(), b.getDate());
if (a.id == 'depaturedate') {
if ($('#arrivaldate').datepicker('getDate') != null) {
//c = $('#arrivaldate').datepicker('getDate', '+3d');
b = CleanDate($("#arrivaldate").val());
c = $.datepicker.parseDate(customFormat(), b);
c.setDate(c.getDate() + 1);
}
}
return {
minDate: c,
maxDate: maxdiff + "d"
} // changes done by parul ends
}
});
$("#depaturedate").change(function () {
var deptdateold = CleanDate($("#depaturedate").val());
var deptdatenew = $.datepicker.parseDate(customFormat(), deptdateold);
var dptday = deptdatenew.getDate();
var dptmon = (deptdatenew.getMonth() + 1);
var dptYear = deptdatenew.getFullYear()
if (dptday.toString().length==1){dptday="0"+dptday;}
if (dptmon.toString().length==1){dptmon="0"+dptmon;}
var departuredatenew = dptday + "/" + dptmon + "/" + dptYear;
$("#calendardept").val(departuredatenew);
$("#depaturedate").val(ChangeDateFormat(deptdatenew));
});
$( "#c_checkout" ).click(function() {
$("#depaturedate").datepicker("show");
});
$( "#c_checkin" ).click(function() {
$("#arrivaldate").datepicker("show");
});
});
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 2);
var tomorrow = new Date(tomorrow).toLocaleDateString('en-GB',
{
day : 'numeric',month : 'short', year : 'numeric'
}).split(' ').join(' ');
$('#arrivaldate').val(tomorrow);
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 3);
var tomorrow = new Date(tomorrow).toLocaleDateString('en-GB',
{
day : 'numeric',month : 'short', year : 'numeric'
}).split(' ').join(' ');
$('#depaturedate').val(tomorrow);
}); //JQuery Document Ready Section Finished Here

Save the selected date from date picker even page refresh

I have a question here regarding how can I save the cookies of a selected date from a date picker even after my page is reload? I have a page which needs to select 3 different dates from date picker, once the date is selected I would like the text box to save the date into cookies until my next change. Would that be possible to make it?
Looking forward for some guidance.
Thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type='text/javascript' href="/jquery-1.5.2.js"></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<title>Blueprint</title>
<style type='text/css'>
#gradient {
color: #000000;
height: 100px;
padding: 10px;
/* For WebKit (Safari, Google Chrome etc) */
background: -webkit-gradient(linear, left top, left bottom, from(#FFD700), to(#fff));
/* For Mozilla/Gecko (Firefox etc) */
background: -moz-linear-gradient(top, #FFD700, #fff);
/* For Internet Explorer 5.5 - 7 */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#FFD700, endColorstr=#FFFFFFFF);
/* For Internet Explorer 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#FFD700, endColorstr=#FFFFFFFF)";
}
</style>
<script type='text/javascript'>
//call for Blueprint
$(function () {
$('.datepower').each(function () {
var disabledDays = [""];
/* utility functions */
function nationalDays(date) {
var m = date.getMonth(),
d = date.getDate(),
y = date.getFullYear();
//console.log('Checking (raw): ' + m + '-' + d + '-' + y);
for (i = 0; i < disabledDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, disabledDays) != -1 || new Date() > date) {
return [true];
}
}
return [true];
}
//Block the Weekends
function noWeekendsOrHolidays(date) {
var noWeekend = $.datepicker.noWeekends(date);
if (noWeekend[0]) {
return nationalDays(date);
} else {
return noWeekend;
}
}
function days() {
var a = $("#datepicker_start").datepicker('getDate');
var b = new Date();
var c = 24 * 60 * 60 * 1000;
var diffDays = Math.round(Math.abs((a - b) / (c)));
$("#totaldays").val(diffDays)
}
$(document).ready(function () {
$.datepicker.setDefaults({
dateFormat: 'dd/mm/yy',
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
constrainInput: true,
beforeShowDay: nationalDays,
});
var selector = function (dateStr) {
var d1 = $('#datepicker_start').datepicker('getDate');
var d2 = $('#datepicker_end').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
$('#totaldays').val(diff);
}
$('#datepicker_start').datepicker({
maxDate: 0,
onSelect: function (selectedDate) {
var minDate = $(this).datepicker('getDate');
if (minDate) {
minDate.setDate(minDate.getDate() + 3);
} //min days requires
$('#datepicker_end').datepicker('option', 'minDate', selectedDate); // Date + 1 or tomorrow by default
days();
}
});
$('#datepicker_end').datepicker({
minDate: 1,
onSelect: function (selectedDate) {
var maxDate = $(this).datepicker('getDate');
if (maxDate) {
maxDate.setDate(maxDate.getDate() - 1);
}
$('#datepicker_start').datepicker('option', 'maxDate', selectedDate); // Date - 1
days();
}
});
$('#datepicker_start,#datepicker_end').change(selector)
});
});
});
//call for Business One
$(function () {
$('.datepower2').each(function () {
var disabledDays = [""];
/* utility functions */
function nationalDays2(date) {
var m = date.getMonth(),
d = date.getDate(),
y = date.getFullYear();
//console.log('Checking (raw): ' + m + '-' + d + '-' + y);
for (i = 0; i < disabledDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, disabledDays) != -1 || new Date() > date) {
return [true];
}
}
return [true];
}
//Block the Weekends
function noWeekendsOrHolidays2(date) {
var noWeekend = $.datepicker.noWeekends(date);
if (noWeekend[0]) {
return nationalDays2(date);
} else {
return noWeekend;
}
}
function days2() {
var a = $("#datepicker_start2").datepicker('getDate');
var b = new Date();
var c = 24 * 60 * 60 * 1000;
var diffDays = Math.round(Math.abs((a - b) / (c)));
$("#totaldays2").val(diffDays)
}
$(document).ready(function () {
$.datepicker.setDefaults({
dateFormat: 'dd/mm/yy',
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
constrainInput: true,
beforeShowDay: nationalDays2,
});
var selector = function (dateStr) {
var d1 = $('#datepicker_start2').datepicker('getDate');
var d2 = $('#datepicker_end2').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
$('#totaldays2').val(diff);
}
$('#datepicker_start2').datepicker({
maxDate: 0,
onSelect: function (selectedDate) {
var minDate = $(this).datepicker('getDate');
if (minDate) {
minDate.setDate(minDate.getDate() + 3);
} //min days requires
$('#datepicker_end2').datepicker('option', 'minDate', selectedDate); // Date + 1 or tomorrow by default
days2();
}
});
$('#datepicker_end2').datepicker({
minDate: 1,
onSelect: function (selectedDate) {
var maxDate = $(this).datepicker('getDate');
if (maxDate) {
maxDate.setDate(maxDate.getDate() - 1);
}
$('#datepicker_start2').datepicker('option', 'maxDate', selectedDate); // Date - 1
days2();
}
});
$('#datepicker_start2,#datepicker_end2').change(selector)
});
});
});
//call for Sigma
$(function () {
$('.datepower3').each(function () {
var disabledDays = [""];
/* utility functions */
function nationalDays3(date) {
var m = date.getMonth(),
d = date.getDate(),
y = date.getFullYear();
//console.log('Checking (raw): ' + m + '-' + d + '-' + y);
for (i = 0; i < disabledDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, disabledDays) != -1 || new Date() > date) {
return [true];
}
}
return [true];
}
//Block the Weekends
function noWeekendsOrHolidays3(date) {
var noWeekend = $.datepicker.noWeekends(date);
if (noWeekend[0]) {
return nationalDays3(date);
} else {
return noWeekend;
}
}
function days3() {
var a = $("#datepicker_start3").datepicker('getDate');
var b = new Date();
var c = 24 * 60 * 60 * 1000;
var diffDays = Math.round(Math.abs((a - b) / (c)));
$("#totaldays3").val(diffDays)
}
$(document).ready(function () {
$.datepicker.setDefaults({
dateFormat: 'dd/mm/yy',
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
constrainInput: true,
beforeShowDay: nationalDays3,
});
var selector = function (dateStr) {
var d1 = $('#datepicker_start3').datepicker('getDate');
var d2 = $('#datepicker_end3').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
$('#totaldays3').val(diff);
}
$('#datepicker_start3').datepicker({
maxDate: 0,
onSelect: function (selectedDate) {
var minDate = $(this).datepicker('getDate');
if (minDate) {
minDate.setDate(minDate.getDate() + 3);
} //min days requires
$('#datepicker_end3').datepicker('option', 'minDate', selectedDate); // Date + 1 or tomorrow by default
days3();
}
});
$('#datepicker_end3').datepicker({
minDate: 1,
onSelect: function (selectedDate) {
var maxDate = $(this).datepicker('getDate');
if (maxDate) {
maxDate.setDate(maxDate.getDate() - 1);
}
$('#datepicker_start3').datepicker('option', 'maxDate', selectedDate); // Date - 1
days3();
}
});
$('#datepicker_start3,#datepicker_end3').change(selector)
});
});
});
</script>
</head>
<body>
<link rel="stylesheet" href="/jquery-ui.css"/>
<script href="/jquery-1.8.3.js"></script>
<script href="/jquery-ui.js"></script>
<table id="gradient" align="center" width="400">
<tr>
<td colspan=1 align=left style="font-family:tahoma;font-size:26px;"><b>Blueprint</b>
<p style="font-family:tahoma;font-size:16px;">Last Situation Date:
<input style="width:80px;background-color:transparent;" type="text" class="datepower"
id="datepicker_start" name="frome" value=""></p></td>
<td style="text-align: right">
<label for="days"></label>
<input type="text" readonly="readonly" class="datepower" name="totaldays" id="totaldays"
style="width:80px;font-size:48px;font-weight:bold;background-color:transparent;border:none;text-align:right;"
onChange="this.form.submit()" value=""><b> Days</b></td>
</tr>
</table>
<table id="gradient" align="center" width="400">
<tr>
<td colspan=1 align=left style="font-family:tahoma;font-size:26px;"><b>Business One</b>
<p style="font-family:tahoma;font-size:16px;">Last Situation Date:
<input style="width:80px;background-color:transparent;" type="text" class="datepower2"
id="datepicker_start2" name="frome2" value=""></p></td>
<td style="text-align: right">
<label for="days2"></label>
<input type="text" readonly="readonly" class="datepower2" name="totaldays2" id="totaldays2"
style="width:80px;font-size:48px;font-weight:bold;background-color:transparent;border:none;text-align:right;"
onChange="this.form.submit()" value=""><b> Days</b></td>
</tr>
</table>
<table id="gradient" align="center" width="400">
<tr>
<td colspan=1 align=left style="font-family:tahoma;font-size:26px;"><b>Sigma</b>
<p style="font-family:tahoma;font-size:16px;">Last Situation Date:
<input style="width:80px;background-color:transparent;" type="text" class="datepower3"
id="datepicker_start3" name="frome3" value=""></p></td>
<td style="text-align: right">
<label for="days3"></label>
<input type="text" readonly="readonly" class="datepower3" name="totaldays3" id="totaldays3"
style="width:80px;font-size:48px;font-weight:bold;background-color:transparent;border:none;text-align:right;"
onChange="this.form.submit()" value=""><b> Days</b></td>
</tr>
</table>
</body>
</html>
You should be able to do what you need using the jquery cookie plugin:
https://github.com/carhartl/jquery-cookie
It allows you to save a cookie option:
$.cookie("test", 1);
Read the cookie option:
var cookieValue = $.cookie("test");
And remove a cookie option:
$.removeCookie("test");
See also this answer: How do I set/unset cookie with jQuery?

Categories

Resources