Bootstrap Datepicker restrict available dates to be selected - javascript

I am using eternicode bootstrap-datepicker;
I would like to know how to configure Bootstrap Datepicker to restrict available dates to be selected. My point is, when some data is ready in a particular date. That date can be selected by user.
At the current point, I am restricting by 7 days from now. However, Saturday and Sundays are days which never have some data;
In this way, I can just show a range of dates, but no "holes" between those ranges. So, I would like to know how to configure Bootstrap Datepicker to restrict available dates to be selected from user.

Bootstrap itself does not have a built in datepicker last i checked. If however you are talking about the bootstrap-datepicker third party library that eternicode wrote.. I believe it supports the same events as the jquery datepicker.. so:
beforeShowDay
Function(Date). Default: $.noop
A function that takes a date as a parameter and returns one of the following values:
undefined to have no effect
A Boolean, indicating whether or not this date is selectable
A String representing additional CSS classes to apply to the date’s cell
An object with the following properties:
enabled: same as the Boolean value above
classes: same as the String value above
tooltip: a tooltip to apply to this date, via the title HTML attribute
usage something like this (below example only allows weekends and the two dates in the custom array below to be selected):
// use this to allow certain dates only
var availableDates = ["15-1-2014","16-1-2014"];
$(function()
{
$('#txtDate').datepicker({
beforeShowDay:
function(dt)
{
// use dt.getDay() to restrict to certain days of the week
// or a custom function like "available" below to do more complex things
return [dt.getDay() == 0 || dt.getDay() == 6 || available(dt), "" ];
}
});
});
function available(date) {
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
if ($.inArray(dmy, availableDates) != -1) {
return true;
} else {
return false;
}
}
Lastly, a working FIDDLE to show above in action.. using jquery datepicker, but same difference...

Make as following:
var available_Dates = ["23/03/2014","21/03/2014"];
$('.datepicker').datepicker({
language: "pt-BR",
autoclose: true,
format: "dd/mm/yyyy",
default: 'dd/mm/yyyy',
beforeShowDay: function(date){
var formattedDate = $.fn.datepicker.DPGlobal.formatDate(date, 'dd/mm/yyyy', 'pt-BR');
if ($.inArray(formattedDate.toString(), available_Dates) == -1){
return {
enabled : false
};
}
return;
}
});

Related

Disable specific times on a specific date using jQuery DateTimePicker

I am trying to disable specific times for specific dates using the jQuery DateTimePicker like this:
jQuery('#datetimepicker').datetimepicker({
disabledDates: ['27/04/2022 14:00'],
format:'d/m/Y H:i'
});
However, this does not work. I can either only disable specific times for every day, or disable specific dates.
That's because the jQuery plugin DateTimePicker's "disabledDates" only accepts and disables days.
https://xdsoft.net/jqplugins/datetimepicker/
It looks like there is no such option for disabling specific times, you could work with only enabling specific times with
https://xdsoft.net/jqplugins/datetimepicker/#allowTimes
jQuery('#datetimepicker').datetimepicker({
datepicker:false,
allowTimes:[
'01:00', '02:00', '03:00',
'04:00', ... , '15:00', '60:00'
]
});
If you would like to continue with jQuery DateTimePicker you would have to write your own function for it
e.g.
jQuery('#datetimepicker').datetimepicker({
format:'d.m.Y H:i',
timepicker: true,
lang: 'en',
onGenerate:function(ct,$i){
//some function here to disable certain times
});
}
}
});
or you could use Bootstrap Datepicker which has an option to do exactly what you want
https://getdatepicker.com/4/Options/#endisabledhours
try this Reference
$(function () {
var disabledDate = ['2020-07-14', '2020-07-15','2020-07-16'];
$('#datetimepickerDemo').datetimepicker({
disabledDates: disabledDate
});
});
Ok I actually managed to figure this out myself. I'm using PHP, but you can essentially just use any multidimensional array and JSON encode it.
$times[]=[
'2022-04-28'=>[
'hour' => 10,
'minute' => 30
]
];
$times[]=[
'2022-04-28'=>[
'hour' => 11,
'minute' => 15
]
];
$times[]=[
'2022-04-29'=>[
'hour' => 13,
'minute' => 30
]
];
$dates=json_encode($times);
Once you have your list of dates and times you can use the onGenerate() function to loop through your dates and add a disabled class to the specific times.
jQuery('#datetimepicker').datetimepicker({
lang:'en',
format:'Y-m-d H:i',
formatDate:'Y-m-d',
step:15,
onGenerate: function(ct, $i){
var date=moment(ct).format('Y-MM-D');
var datesArray=<?echo $dates;?>;
$.each(datesArray, function(i, dates){
if(date in dates){
var times=dates[date];
$.each(times, function(index, time){
var hour=times['hour'];
var minute=times['minute'];
var $object=$('[data-hour="' + hour + '"][data-minute="' + minute + '"]');
$object.addClass('xdsoft_disabled');
});
}
});
}
});
Please note: you will need to use the exact same date format for your array and jQuery function. Also, my step is set to 15 minute increments. So this only disables that exact step.

How to grab selected dates from flatpickr

I have a range date picker at the moment.
<input id="rangeDatepicker2" class="g-font-size-12 g-font-size-default--md" type="text" data-rp-wrapper="#rangePickerWrapper2" data-rp-type="range" data-rp-date-format="d M Y" data-rp-default-date='["01 Jan 2016", "31 Dec 2017"]'>
I would like to reuse the dates but I am unable to select them for all scenarios. I tried the code below which works great if the date selected are in the same month. But my issue is this bit of code doesn't work if the dates span multiple months.
$("#rangeDatepicker2").change(function () {
var dates = $('.selected');
if (dates.length == 2) {
var start = dates[0].dateObj;
var end = dates[1].dateObj;
//interact with selected dates here
}
});
May I ask how do I properly grab selected date range of a flatpickr.
Many input plugins actually pass the values in a onChange handler. The values are available there.
Solution
Pass down an onChange handler when initializing flatpickr:
$("#rangeDatepicker2").flatpickr({
mode: 'range',
onChange: function(dates) {
if (dates.length == 2) {
var start = dates[0];
var end = dates[1];
// interact with selected dates here
}
}
})
Demo
onChange documentation:
https://flatpickr.js.org/events/#hooks

Linked DateTimepickers should not allow certain dates

I am using a boostrap-datetimepicker plugin and on my page i have 2 Linked Pickers(named startPicker and endPicker) i have configured both the pickers through their options not allow the future date but i a have a startPicker that should only allow selection the past dates not including today and i have an endPicker that should only allow selection of past dates including today starting from the date of selected startPicker. With configuration for the endPicker the user is able to select the date lower than the selected date in startPicker. Is there a way to get the selected date in startPicker ?
$(function (){
const yesterdayDate = new Date();
yesterdayDate.setDate(yesterdayDate.getDate() - 1); //Yesterday date
$('#startPicker').datetimepicker({
maxDate: yesterdayDate,
});
$('#endPicker').datetimepicker({
minDate: yesterdayDate,
maxDate: new Date()
});
});
You can use:
$('#endPicker').datetimepicker({
minDate: yesterdayDate,
maxDate: new Date()
});
$('#Startpicker').on('dp.change', (selected) => {
$('#endPicker').data("DateTimePicker").minDate(selected.date);
})
This code watches for changes to startPicker then updates endPicker's minDate.
Hopefully, this helps.

Bootstrap datetimepicker: set view only date, day not preselected

I'm using this bootstrap datetime picker.
Here's my code:
var dp = $('#datetimepicker')
.datetimepicker({
viewDate: setViewDate(),
format: 'MM/DD/YYYY',
maxDate: moment(currentDate, 'MM/DD/YYYY'),
minDate: moment(currentDate).subtract(200, 'years')
});
function setViewDate (){
if (!$('#datetimepicker').find('input').val()) {
return moment(new Date()).subtract(30, 'years'); }
else { return false; }
}
How the above works is if the datetimepicker input doesn't have any value, when we open the picker, the date in the picker (and not the actual input date) should be today - 30 years.
This works fine except the day in the picker is not selected, see below:
Q: How can I preselect the day also in the picker? (not the actual input value)
You can try setting date like this:
$("#datePicker")
.datepicker({
format: "mm/dd/yyyy",
autoclose: true
});
$("#datePicker").datepicker("setDate", new Date());
So, if you want other date, you can make it as new Date("October 13, 2014).
You need to update the date in the datepicker as well
$('#datetimepicker').datepicker('update', moment(new Date()).subtract(30, 'years'));
Hi I took a quick look at the reference doc , I think you should use "defaultViewDate" option defaultviewdate

How to set the date in materialize datepicker

I am using materializecss.com Datepicker. When i try to set date with jquery, the date doesn't get set. Here is my Code :-
// Materialize Date Picker
window.picker = $('.datepicker').pickadate({
selectMonths: true, // Creates a dropdown to control month
selectYears: 100, // Creates a dropdown of 15 years to control year
format: 'dd/mm/yyyy'
});
<input type="text" id="Date" class="datepicker" />
On Click event of a Button , I am setting the date :-
$("#Date").val('23/01/2015');
When i open the datepicker it shows me today's date.
How to set the date in materialize datepicker?
Materialize datepicker is a modified pickadate.js picker.
Accodging to their API docs, this is how to set the picker:
Get the picker:
var $input = $('.datepicker').pickadate()
// Use the picker object directly.
var picker = $input.pickadate('picker')
Set the date:
// Using arrays formatted as [YEAR, MONTH, DATE].
picker.set('select', [2015, 3, 20])
// Using JavaScript Date objects.
picker.set('select', new Date(2015, 3, 30))
// Using positive integers as UNIX timestamps.
picker.set('select', 1429970887654)
// Using a string along with the parsing format (defaults to `format` option).
picker.set('select', '2016-04-20', { format: 'yyyy-mm-dd' })
just add the format you want your date looks like in the attributes of your element.
$('.datepicker').pickadate({
selectMonths: true, // Creates a dropdown to control month
selectYears: 15, // Creates a dropdown of 15 years to control year
format: 'dd-mm-yyyy' });
You can use methods of datepicker which are present in V1.0.0-rc.2.
document.addEventListener('DOMContentLoaded', function() {
var options = {
defaultDate: new Date(2018, 1, 3),
setDefaultDate: true
};
var elems = document.querySelector('.datepicker');
var instance = M.Datepicker.init(elems, options);
// instance.open();
instance.setDate(new Date(2018, 2, 8));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<input type="text" class="datepicker">
defaultDate will set a default Date that will be shown in input-field of datepicker without even opening the picker.
instance.setDate() will select the date in datepicker when you'll open it.
Note- new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
The argument monthIndex is 0-based. This means that January = 0 and December = 11
Picker - Materialize
MDN - Date
Alle answers with pickadate() don't work anymore in newer versions of Materialize. The method is now named datepicker(). Here's my code snippet:
var element = document.querySelector('.datepicker');
M.Datepicker.getInstance(element).setDate(new Date(2018,8,7), true);
As per the docs materializecss.com
Check the Date format options.
// date picker
$(document).ready(function(){
$('.datepicker').datepicker( {"format":'dd-mm-yyyy'} ).datepicker("setDate", new Date());
});
You can remove and change the code to below if you do not need current date as highlighted in calendar,
// date picker
$(document).ready(function(){
$('.datepicker').datepicker( {"format":'dd-mm-yyyy'});
});
You can pass in the options that you want to default to on init.
For example the below js code would work with markup:
const elems2 = document.querySelectorAll('.datepicker');
for (element of elems2) {
const date = element.dataset.defaultDate
if (date !== undefined) {
M.Datepicker.init(element, {defaultDate: new Date(date), yearRange: 15})
}
else {
M.Datepicker.init(element, {})
}
}
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<input class="validate datepicker valid" required="required" data-default-date="2009-07-11 10:14:47 -0700" name='picker' type="text">
<label for="picker" class="active">Date Picker 10 years ago</label>
If you are using angular, or something similar, in order to manage your web application and you are not able to instance the Datepicker object, according to the materialize documentation, using jQuery you can refer to these methods of the object:
$('.datepicker').datepicker('setDate', new Date());
In the first parameter, in this case setDate, you may specify the method name that you are about to use. In the second parameter, in this case new Date(), you will pass the value to the function (if any).
In the example, that line will update the date of all datepickers with the class .datepicker to today.
var $input = $('.datepicker').pickadate()
// Use the picker object directly.
var picker = $input.pickadate('picker')
Heading
$('#elementID').pickadate('picker').set('select', '21/05/2017', { format: 'dd/mm/yyyy' }).trigger("change");
This should suit your needs in one line. Trigger change you may need or maybe not, depends your situation, like me i need it for validation to trigger. Also include with format date just in case some people need it.
watch out for your css and js version of materialize:
if in the <head> you have
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
then stick to it having same JS version
so that you can use $('.datepicker').pickadate('picker').set('select','your parsed date',{format:'your format'}).trigger('change')
If version is 1.0.0 then you will have to use
$('.datepicker').datepicker();

Categories