Highlight specific date when datepicker shown - javascript

I have this simple datepicker jQuery, and in my application my users can go back to the past, but not future. I want to show the current day base on the date param in the url browser.
Let's say
var url_string = window.location.href;
var url = new URL(url_string);
var dateParam = url.searchParams.get("date"); <<----- current date
I have
$(".clock").click(function() {
$( "#expiryDate" ).datepicker('setDate', date); <<---- Note here
$("#expiryDate").datepicker({
dateFormat: 'yy-mm-dd',
defaultDate: date,
showAnim: "fold",
gotoCurrent: true,
maxDate: 0,
onSelect: function() {
var dateSelected = $(this).datepicker('getDate');
dateSelected = moment(dateSelected).format('YYYY-MM-DD');
// $( "#expiryDate" ).datepicker('setDate', dateSelected);
playSound('forward');
if(dateParam == null) {
var url = document.location.href+"&date="+dateSelected;
}else {
var url = document.location.href;
url = url.replace(dateParam,dateSelected);
}
document.location = url;
}
});
$('#expiryDate').datepicker('show');
});
Even if today is 05/06/2021, users can go back to the past, and see what happened on that day. So when user selected 02/03/2021. I want to highlight that date 02/03/2021. It seems working only if I clicked on my date twice.
Notice only second clicked 3 started to highlight!
How do I make it highlight on first clicked ?

I want to highlight that date 02/03/2021. It seems working only if I clicked on my date twice.
If removed the following code:
var dateSelected = $(this).datepicker('getDate');
dateSelected = moment(dateSelected).format('YYYY-MM-DD');
This can easily be replaces by the onChange function parameter, for more info, take a look at the documentation.
Replaced by:
onSelect: function(dateSelected) {
With that in mind, I've created some sort of [mre] from the code above. This seems to work as expected:
The url_string date is selected on load
On press, the new date is highlighted instantly
var url_string = 'https://example.com?date=2021-05-02'; // DEBUG
var url = new URL(url_string);
var dateParam = url.searchParams.get("date");
console.log('dateParam', dateParam);
$(".clock").click(function() {
$("#expiryDate").datepicker({
dateFormat: 'yy-mm-dd',
defaultDate: dateParam,
showAnim: "fold",
gotoCurrent: true,
maxDate: 0,
onSelect: function(dateSelected) {
console.log('onSelect', dateSelected);
if (dateParam == null) {
var url = document.location.href+"&date="+dateSelected;
} else {
var url = document.location.href;
url = url.replace(dateParam,dateSelected);
}
}
});
$('#expiryDate').datepicker('show');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class='clock'>🕑
<div id='expiryDate' />
</div>

Shooting a bit in the dark for now, since we have low info:
According to your snippets:
var dateParam = url.searchParams.get("date"); <<----- current date
And
$( "#expiryDate" ).datepicker('setDate', date); <<---- Note here
The problem is that you define dateParam while you use date.
It's hard to tell if other code define the date variable, but as a starter, I'd make sure that your date is correctly set...
console.log(date); // Make sure it logs the correct date.
$( "#expiryDate" ).datepicker('setDate', date); <<---- Note here

It is due to the lifecycle of the datepicker. The datepicker will be initialized as
$("#expiryDate").datepicker({});
If you call
$("#expiryDate").datepicker('setDate', date);
Before the datepicker be initialized, that will nothing to do with it at the first time.
At the second time, because of the datepicker was initialized. So, everything works fine. Moreover, once you set the date, it not needs to default date.
Due to reasons of above, the code should be modified as
$(".clock").click(function() {
$("#expiryDate").datepicker({
dateFormat: 'yy-mm-dd',
showAnim: "fold",
gotoCurrent: true,
maxDate: 0,
onSelect: function() {
var dateSelected = $(this).datepicker('getDate');
dateSelected = moment(dateSelected).format('YYYY-MM-DD');
// $( "#expiryDate" ).datepicker('setDate', dateSelected);
playSound('forward');
if(dateParam == null) {
var url = document.location.href+"&date="+dateSelected;
}else {
var url = document.location.href;
url = url.replace(dateParam,dateSelected);
}
document.location = url;
}
});
$("#expiryDate").datepicker('setDate', date); <<---- Note here
$("#expiryDate").datepicker('show');
});

Related

Get value from input in function that not in $(document).ready(JS)

I have JS script file.
In this file I have code that populate inputs with value from calendar
Here is code.
$(document).ready(function () {
columnSettings = $('#visibleColumns').val();
SetColumnCheckboxes();
$('#tableDetails').DataTable({
'columnDefs': columnDefs,
'sDom': '<"table-options"<"top length"l><"top paging"p><"top filtering"f>>rt<"bottom"i>',
'sScrollY': '1px',
'scrollX': true,
'autoWidth': true,
'lengthMenu': [[-1, 10, 25, 50, 100], [dictionary.find('all'), 10, 25, 50, 100]],
'language': dataTablesLanguage
});
//cultureTwoLetterName is a global variable from the view that contains the two letter iso language name
$.datepicker.setDefaults($.datepicker.regional[cultureTwoLetterName]);
$('#calendar').weekMonthDatepicker({
changeMonth: true,
dateFormat: 'yy-mm-dd',
showWeek: true,
firstDay: 1,
weekHeader: '<span class="glyphicon glyphicon-arrow-down"></span>',
minDate: -loggingRetention,
maxDate: '+0D',
weekSelection: true,
weekSelected: SelectionCallback,
monthSelection: true,
monthSelected: SelectionCallback
});
$('#startDate').datepicker({
changeMonth: true,
dateFormat: 'yy-mm-dd',
firstDay: 1,
minDate: -loggingRetention,
maxDate: '+0D'
});
$('#endDate').datepicker({
changeMonth: true,
dateFormat: 'yy-mm-dd',
firstDay: 1,
minDate: -loggingRetention,
maxDate: '+0D'
});
$('#selectGroups').on('change', function () {
PopulateSelectVehicles();
});
$('#selectVehicles').on('change', function () {
var imei = $(this).val();
var device = getDevice(imei);
configureReportpageForDevice(device);
var start = $('#calendar').weekMonthDatepicker('getStartDate');
var stop = $('#calendar').weekMonthDatepicker('getEndDate');
var ui;
if (start != null && stop != null) {
var ui = { 'startDate': start, 'endDate': stop };
}
PopulateTableDetails(null, ui);
});
$('#calendar').on('change', function () {
$('#startDate').val(moment($(this).val()).format('DD/MM/YYYY'));
$('#endDate').val(moment($(this).val()).format('DD/MM/YYYY'));
startdate = $('#startDate').val();
end = $('#endDate').val();
alert(end);
var start = $('#calendar').weekMonthDatepicker('getStartDate');
var stop = $('#calendar').weekMonthDatepicker('getEndDate');
var ui;
if (start != null && stop != null) {
ui = { 'startDate': start, 'endDate': stop };
}
PopulateTableDetails(null, ui);
});
$('#startDate').on('change', function () {
$(this).val(moment($(this).val()).format('DD/MM/YYYY'));
if ($('#endDate').val() == '' || moment($('#endDate').val(), 'DD/MM/YYYY') < moment($(this).val(), 'DD/MM/YYYY')) { //endDate niet ingevuld of < startDate --> endDate = startDate
$('#endDate').val($(this).val());
}
var start = moment($(this).val(), 'DD/MM/YYYY');
var stop = moment($('#endDate').val(), 'DD/MM/YYYY');
var ui = { 'startDate': start, 'endDate': stop };
PopulateTableDetails(null, ui);
});
$('#endDate').on('change', function () {
$(this).val(moment($(this).val()).format('DD/MM/YYYY'));
if ($('#startDate').val() == '' || moment($('#startDate').val(), 'DD/MM/YYYY') > moment($(this).val(), 'DD/MM/YYYY')) { //startDate niet ingevuld of > endDate --> startDate = endDate
$('#startDate').val($(this).val());
}
var start = moment($('#startDate').val(), 'DD/MM/YYYY');
var stop = moment($(this).val(), 'DD/MM/YYYY');
var ui = { 'startDate': start, 'endDate': stop };
PopulateTableDetails(null, ui);
});
});
I need to get values from startDate and endDate
I can do it writing startdate = $('#startDate').val(); in $('#calendar').on('change', function () { function.
But I have function out of document.ready block, that connected with map and cannot be used in document.ready block.
Here is code of this function
function getDriving() {
var startdatevalue = startdate;
alert(startdatevalue);
var url = $('#map').data('request-url2');
$.getJSON(url,
function (data) {
var marker = [];
$.each(data,
function (i, item) {
marker.push({
'location': new google.maps.LatLng(item.Latitude, item.Longitude),
'map': map,
'weight': item.Speed,
'radius': 10
});
});
var pointArray = new google.maps.MVCArray(marker);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
});
};
And when I write var startdatevalue = startdate;
alert(startdatevalue); in it it is null.
How I can get value in this function correctly?
Here is full code of js Code
I tried to write initMap and other related functions in document.ready, but I get initMap not a function error. Because of this line in View <script async src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCea6m‌​L2cqwVid2ESIjuJ0C31R‌​bNVQNPY0&libraries=v‌​isualization&callbac‌​k=initMap"> </script>
Thank's for help
This is a common problem. It's all about scope. Any var's you cast in the .ready event are only available in that scope (function).
So the work-around is to cast the var outside that function. (global scope)
If you have other modules/functions that need to read these vars your best bet is make your own app object and set the vars in that, you can then read those vars elsewhere in your app code.
var app = {};
..
$(document).ready(function () {
app.startdate = //some value
..
});
Now anywhere else in your app you can access that global object
console.log(app.startdate)
I have used a global object as you may need to have start, end date and other vars that can be accessed by the outside modules
You can just do
var startdate
Outside the ready function and that will also work.
The problem with this design method is that the var may not be set when the 2nd functions requests it.
This problem is solved by either passing the var in directly to the other function. Or using an event drive system, where by function 2 subscribes to an event on function 1 that passes the var as it is set, or changed.

disable the past date and month using full calendar

How to disable the past date and the past month using full calendar in select option I tried out with this function in full calendar
select: function(start, end, allDay) {
var check = $.fullCalendar.moment(start).format('DD-MM-YYYY');
var today = $.fullCalendar.moment(new Date()).format('DD-MM-YYYY');
if (check >= today) {
}
}
but not working, it disables next month also. if it possible in javascript? also it fine.Demo link
Here is some googled code snippet.
you can add this code in your select function.
select: function(start, end, allDay) {
var check = $.fullCalendar.formatDate(start,'yyyy-MM-dd');
var today = $.fullCalendar.formatDate(new Date(),'yyyy-MM-dd');
if(check < today)
{
// Previous Day.
}
else
{
// Right Date
}
},
Your condition totally works.
select: function(start, end, allDay) {
var check = $.fullCalendar.formatDate(start, 'yyyy-MM-dd');
var today = $.fullCalendar.formatDate(new Date(), 'yyyy-MM-dd');
if (check >= today) {
// True conditions
}
}
Please check this fiddle
You can disabling past date and the past month of a full calendar using minDate attribute of datepicker.
var dateToday = new Date();
$('#visit').datepicker({
minDate: dateToday
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link href="https://davidwalsh.name/demo/jquery-ui-css/custom-theme/jquery-ui-1.7.2.custom.css" rel="stylesheet"/>
<input type='text' id='visit' />

jQuery UI Datepicker: restricting to fortnight

I've done some searching and can't really seem to find a specific example of what I'm looking for (JS isn't my strong point). If there is another answer already provided, I apologise and would be eternally grateful for the link.
I'm currently building a pay calculator in PHP, with the datepicker on my front page to ensure consistency. We get paid fortnightly, and I want to make only those fortnightly dates available for selection. I've disabled all days bar Saturdays, but it allows all Saturdays. I figure there is probably a for loop or something I can use to count every second Saturday from a specified date to ensure the correct dates are shown, but as I said above, I'm not familiar with JS. (I would like to count from a specified date so it auto-updates and I don't have to hardcode the fortnight dates.)
My code was as follows:
$(function() {
$( "#datepicker" ).datepicker({
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
dateFormat: "dd-mm-yy",
beforeShowDay: nonWorkingDates,
});
function nonWorkingDates(date){
var day = date.getDay(), Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6;
var closedDays = [[Sunday], [Monday], [Tuesday], [Wednesday], [Thursday], [Friday],];
for (var i = 0; i < closedDays.length; i++) {
if (day == closedDays[i][0]) {
return [false];
}
}
return [true];
}
});
But thanks to Badri, I've slimmed it down to:
$(function() {
$( "#datepicker" ).datepicker({
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
dateFormat: "dd-mm-yy",
beforeShowDay: nonWorkingDates
});
function nonWorkingDates(date){
if (date.getDay() != 6) {
return [false, '', 'selected'];
}
return [true, ''];
}
});
As a related matter (which I'm happy to make a separate question if required), can I make datepicker show just those dates that you can select from? Or is there an alternative to datepicker that someone can suggest to achieve this?
Cheers
Refer to this faq that shows how to allow users to select only specific days in a week:
http://jqfaq.com/how-to-restrict-date-selection-to-specifc-week-days-in-the-dropdown/
To allow every other saturdays from today only, your code would look slightly different like this:
function beforeShowDayHandler(date) {
var today = new Date();
if (date < today || date.getDay() != 6) {
return [false, '', 'selected'];
} else {
var day = today.getDay();
var comingSat = new Date();
comingSat.setDate(comingSat.getDate() + 6 - day);
var diffDays = dateDiffInDays(comingSat, date);
var noOfWeeksAway = diffDays / 7;
if ((noOfWeeksAway % 2 == false)) return [false, '', 'selected'];
}
return [true, ''];
}
Full functional fiddle here:
http://jsfiddle.net/badri_cr/VNNYP/
use the options:
minDate: 0,
maxDate: '+14'
to limit the datepicker to the next fortnight.

datepicker date is not accurate in ipad

I've developed a jQuery datepicker instance using the following code.
$(function() {
$('.datepicker').datepicker({
inline: true,
showButtonPanel: true, //Default Button Panel is customized in jQuery UI Soucre - Line Number : 9265
showOtherMonths: true,
showOn: "both",
buttonImage: "/images/calendar.png",//custom icon trigger -> positioned in CSS
buttonImageOnly: true,
//beforeShowDay:function(date){
//var blockDates = [""];
//var currentDateString = $.datepicker.formatDate(date);
//return [blockDates.indexOf(currentDateString) == -1 ];
//},
onSelect:function(date,inst){
if(inst.id != "to" && date != ""){
var numOfDays = 2;
var date = $.datepicker.parseDate('mm/dd/yy', date);
date.setDate(date.getDate('mm/dd/yy') + numOfDays);
setTimeout(function () {
$("#to").datepicker('option', 'minDate', date);
$("#to").datepicker('show');
$("#to").datepicker('setDate',date.toLocaleDateString());
}, 10);
}
}
});
});
I've got two inputs with datepicker instances. In the first I select a date and by using the date I populate the second date. When I test this on a desktop and I get the correct date. But the thing is I tested this on an iPad and the calculated date is not advanced by two days. the date is advanced by 7 months! I have no idea what's wrong with the code! any help?
I've tested in both safari + google chrome for ipad. the result is same.
Date.getDate() does not accept any parameters.
datepicker.setDate() happily accepts the JavaScript Date
Try revising your code like this:
onSelect: function (date, inst) {
if (inst.id != "to") {
var numOfDays = 2;
var date = $.datepicker.parseDate("mm/dd/yy", date);
date.setDate(date.getDate() + numOfDays);
$("#to").datepicker("option", "minDate", date);
$("#to").datepicker("setDate", date);
setTimeout(function () {
$("#to").datepicker("show");
}, 10);
}
}

datepicker onselect is not firing From gridmvc.js plugin

dateContainer.datepicker({
defaultDate: this.filterValue,
changeMonth: true,
changeYear: true,
dateFormat: 'MM-dd-yyyy',
onSelect: function (dateText, t) {
var type = $context.container.find(".grid-filter-type").val();
$context.cb(type, dateText);
}
});
I'm using gridmvc.js and bootstrap-datepicker.js plugin.
OnSelect event is not firing anyway. I don't know what is the reason ?
I don't know because of what, the problem is occurred. But I've found the temporary solution for this. For the solution, you've to change one line of code in bootstrap-datepicker.js. (Check about the license before you change and use the plugin)
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
var day = 1;
var month = target.parent().find('span').index(target);
var year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
} else {
var year = parseInt(target.text(), 10)||0;
var day = 1;
var month = 0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
}
this.showMode(-1); this.fill();
Here the problem is occured because of this.fill() is called.
if you comment this line in plugin, datepicker won't hide any way on month and year change. Or you can change by following,
if (target.is('.month')) {
if (!this._o.changeMonth) {
this.fill();
}
}
else {
if (!this._o.changeYear) {
this.fill();
}
}
Then this will work, based on the parameter you've given while creating datepicker.

Categories

Resources