jQuery datetimepicker disable specific time by date dynamically - javascript

I have a code here of my datetimepicker which will take away specific hours by date.
var specificDates = ['24/12/2014', '17/12/2014'];
var hoursToTakeAway = [[14, 15],[17]];
$('#from_date').datetimepicker({
format: 'd.m.Y H:i',
timepicker: true,
lang: 'en',
onGenerate: function (ct, $i) {
var ind = specificDates.indexOf(ct.dateFormat('d/m/Y'));
$('.xdsoft_time_variant .xdsoft_time').show();
if (ind !== -1) {
$('.xdsoft_time_variant .xdsoft_time').each(function (index) {
if (hoursToTakeAway[ind].indexOf(parseInt($(this).text())) !== -1) {
$(this).hide();
}
});
}
}
});
My problem is how to manipulate it dynamically like this:
if I select in my datetimepicker:
07/05/2015 -take away hours: 1,2
13/05/2015 -take away hours: 3,4,5
How would I do that?

Related

Allow date less than minDate in flatpickr

I have the following code:
if (setToToday) {
this.flatpickr({
minDate: 'today',
defaultDate: new Date( $(this).attr("date")),
});
} else {
flatpickr(this).setDate(new Date( $(this).attr("date") ));
}
Now what I would like to do is to show the user a date value less than today if the attr(date) is lesser today. Suppose today is 2021-03-03 and the previously selected value was 2021-02-02, I would like to allow the user to select that previous date or any date from today. Nothing in between. How can I do that in flatpickr?
If you’d like to make certain dates unavailable for selection, there are multiple methods of doing so.
Disabling specific date
Disabling a date range
Disabling dates using a function
Disabling specific dates
{
disable: ["2025-01-30", "2025-02-21", "2025-03-08", new Date(2025, 4, 9) ],
dateFormat: "Y-m-d",
}
Disabling range(s) of dates:
{
dateFormat: "Y-m-d",
disable: [
{
from: "2025-04-01",
to: "2025-05-01"
},
{
from: "2025-09-01",
to: "2025-12-01"
}
]
}
Disabling dates by a function:
{
"disable": [
function(date) {
// return true to disable
return (date.getDay() === 0 || date.getDay() === 6);
}
],
"locale": {
"firstDayOfWeek": 1 // start week on Monday
}
}
Refer to the official documentation for more

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.

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