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?
Related
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"/>
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.
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
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>
I am writing following code.
<!doctype html>
<html><head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Icon trigger</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js">
</script> <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js">
</script>
<script>
$(function () {
$("#datepicker").datepicker({
minDate: -0,
maxDate: "+1M +2D",
showOn: "button",
buttonImage: "calendar.png",
buttonImageOnly: true,
dateFormat: 'D dd MM yy' });
$.datepicker.formatDate('yy-mm-dd');
});
function updateDate(){
var inputDate=document.getElementById('datepicker').value;
var selectedDate=new Date(inputDate);
var today=new Date();
var tomorrow=new Date();
tomorrow.setDate(today.getDate()+1);
selectedDate.setHours(0,0,0,0);
today.setHours(0,0,0,0);
tomorrow.setHours(0,0,0,0);
var DaysFull=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
var DaysShort=["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
var MonthsFull=["January","February","March","April","May","June","July","August","September","October","November","December","January"];
var MonthsShort=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan"];
var finalDate=DaysShort[selectedDate.getDay()]+" "+selectedDate.getDate()+" "+MonthsFull[selectedDate.getMonth()];
if(selectedDate.getTime() == today.getTime()){
document.getElementById('datepicker').value=finalDate+" (Today)";
}
else if(selectedDate.getTime() == tomorrow.getTime()){document.getElementById('datepicker').value=finalDate+" (Tomorrow)";}
else {document.getElementById('datepicker').value=finalDate;}
}
function addDaysToDate() {
var date1= document.getElementById('datepicker').value;
var date = new Date( Date.parse( date1 ) );
date.setDate( date.getDate() + 1 );
alert(date);
document.getElementById('datepicker').value=date;
}
</script>
</head>
<body>
<form><input type="text" id="datepicker" onchange="javascript:updateDate()" style="width:160px" />
<button onclick="addDaysToDate()">add</button></form>
</body></html>
I have a button on click of which date in text box should be increase by 1 upto next 32 days and not beyong but above code increases the date and value disappears from the text box rather than showing ...
You are setting a date field to set additional text so the date in not a valid date object and break the plugin.
You are using the datepicker plugin so you can use getDate and setDate methods to get/set the values as date objects.
Docs: http://api.jqueryui.com/datepicker/#method-getDate and http://api.jqueryui.com/datepicker/#method-setDate
I changed your code by using an additional field to show if the date is today or tomorrow:
$(function () {
$("#datepicker").datepicker({
minDate: -0,
maxDate: "+1M +2D",
showOn: "button",
buttonImage: "calendar.png",
buttonImageOnly: true,
dateFormat: 'D dd MM yy'
});
$("#datepicker").change(function () {
updateDate();
});
$("#addDate").click(function () {
addDaysToDate();
});
});
function updateDate() {
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1);
var date2 = $('#datepicker').datepicker('getDate');
date2.setHours(0,0,0,0);
today.setHours(0,0,0,0);
tomorrow.setHours(0,0,0,0);
if (date2.getTime() == today.getTime()) {
$('#todtom').text(" (Today)");
} else if (date2.getTime() == tomorrow.getTime()) {
$('#todtom').text(" (Tomorrow)");
} else {
$('#todtom').text("");
}
}
function addDaysToDate() {
var date2 = $('#datepicker').datepicker('getDate');
date2.setDate(date2.getDate() + 1);
$('#datepicker').datepicker('setDate', date2);
$('#datepicker').change();
}
I changed the code to use full jQuery code not a mix of jQuery and JS for DOM manipulation.
Demo: