how to generate datepicker bootstrap datesDisabled dynamically - javascript

i am trying to generate dynamically the disabled dates using ajax call , and pass the result to datesDisabled option of bootstrap datepicker , or for other alternative pass the result to beforeShowDay option , but it doesn't work for dynamically created array Result, but it worked fine for hard coded array.
In fact , when i use dynamically generated Array , the Date Array is passed to beforeShowDay in the second time i choose dates from datepicker, and it is not passed to the picker in the first time,
but when hard coded, the array is perfectly passed to beforShowDay from the first time the picker is clicked.
the dynamically created array is
Date Array:
2021-03-17,2021-03-18,2021-03-24,2021-04-06,2021-04-07,2021-04-13,2021-04-14
so what am doing wrong?
<script type="text/javascript">
$(document).ready(function () {
function GetHolidayOrStopDay() {
// alert("Get Holidays");
var DateArray = new Array();
$.ajax({
type: "POST",
url: "timeObjectWebService.asmx/GetHolidaysAndDisabledDays",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var JsonObject = JSON.parse(data.d);
$(JsonObject).each(function (index, da) {
var testJsonDate = formatJsonDate(da.HolidayDate);
var options = {
year: "numeric",
month: "numeric",
day: "numeric",
};
var result = testJsonDate.toLocaleDateString("en", options);
result = new Date(result);
var DateResult = formatDate(result);
//if (index < (JsonObject.length - 1)) {
DateArray.push(DateResult);
// }
// else {
// DateArray += DateResult;
//}
console.log("rrr : " + DateResult);
});
//DateArray += ']';
console.log("Date Array :" + DateArray);
//console.log("1 : " + DateArray[1]);
},
error: function (err) {
//alert("test err");
console.log(err);
},
});
//alert(DateArray);
TestdisabledDays = DateArray;
return DateArray;
}
function formatJsonDate(jsonDate) {
var dat = new Date(parseInt(jsonDate.substr(6)));
return dat;
}
var enableDays = ["2021-03-30"];
var disabledDays = [
"2021-03-23",
"2021-03-22",
"2021-03-30",
"2021-03-29",
"2021-03-28",
"2021-04-01",
]; //for this hardcoded array everything works fine
var TestdisabledDays = new Array();
TestdisabledDays = GetHolidayOrStopDay();
//GetHolidayOrStopDay();
function formatDate(d) {
var day = String(d.getDate());
//add leading zero if day is is single digit
if (day.length == 1) day = "0" + day;
var month = String(d.getMonth() + 1);
//add leading zero if month is is single digit
if (month.length == 1) month = "0" + month;
return d.getFullYear() + "-" + month + "-" + day;
}
$("#dtpicker").datepicker({
format: "dd-mm-yyyy",
autoclose: true,
startDate: "0d",
datesDisabled: [TestdisabledDays],
beforeShowDay: function (date) {
//alert("from picker");
//for disable weekends :
var dayNr = date.getDay();
if (dayNr == 0 || dayNr == 6) {
if (enableDays.indexOf(formatDate(date)) >= 0) {
return true;
}
return false;
}
if (TestdisabledDays.indexOf(formatDate(date)) >= 0) {
console.log("index of " + TestdisabledDays.indexOf(formatDate(date))); //disabledDays
console.log("TestdisabledDays = " + TestdisabledDays); //disabledDays
return false;
}
return true;
},
});
});
</script>

ajax and datepicker init are running asychronically the picker is initializing before the ajax is done(that's why it is working second time), to solve this you might consider using $.when (api.jquery.com/jquery.when) or init the datepicker then when ajax return response use the methods of the datepicker itself (bootstrap-datepicker.readthedocs.io/.../methods...) hope this helps

Related

How to disable click in past days fullcalendar

I try to disable clickable past days.
I'm using dateClick but can't pass multiple args and have error:
*Uncaught TypeError: date.format is not a function
My function:
EDIT:
Dateclick function with ajax.
Now don't know how to disable click, when past days
dateClick: function (info, jsEvent, view, date) {
let currDate = info.dateStr;
// if (moment().format('YYYY-MM-DD') === currDate || date.isAfter(moment())) {
// return false;
// } else {
//
// alert('Date: ' + currDate);
// alert('ID: ' + $('#reservation-form #select-service').val());
// }
let selectServiceVal = $('select#select-service').val();
if (!selectServiceVal) {
alert('Najpierw wybierz usługę');
} else {
dateValue.val(currDate);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: getFreeHorus + selectServiceVal + '/' + currDate,
dataType: 'json',
method: "POST",
data: {
"id": selectServiceVal,
"date": currDate
},
beforeSend: function () {
$(".calendary-loader").css('display', 'block');
},
success: function (data) {
$(".calendary-loader").css('display', 'none');
if (data.message) {
alert('Wybierz poprawną datę')
}
displayHours(data.availableHours);
},
error: function () {
$(".calendary-loader").css('display', 'none');
alert('Błąd serwera, spróbuj później')
}
});
}
}
You can use select. This is how I did mine:
select: this.handleDateClick.bind(this),
//the handleDateClick funtion
handleDateClick(arg: any) {
let todaysDate = new Date();
let formattedDate = moment(todaysDate).format("YYYY-MM-DDTHH:mm:ss"); //formatted version of todays date so a comparison can be made
let s1 = arg.startStr;
let s2 = arg.endStr;
let currentdate = moment().isUTC();
let newDateObj = moment(s1).add(15, "m").format("YYYY-MM-DDTHH:mm:ss");
if (s1 < formattedDate) {
//This checks if time is in the past. If so,
alert("This date is in the past")

set the disabled dates of a datepicker by a database json list of timestamp dates

I want to disable dates in flatpicker plugin by a list from the database. this is the code to get them from the database
public List<DateTime> DisablingDates()
{
List<DateTime> dates = new List<DateTime>();
var groups = OrderContext.Collection().GroupBy(o => o.DueDate);
foreach (var g in groups)
{
if (g.Count() == 2)
{
var val = g.Key.Date;
val.ToString("dd/MMM/yyyy");
dates.Add(val);
}
}
return dates;
}
I passed the list through viewbag to the jquery but the plugin stopped working.. the browser debugger showes the DisabledDates array with timestamp dates , so I tried to convert them to readble dates but the alert function doesn't show the values.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.6/flatpickr.min.js"></script>
<script>
$("#datepicker").flatpickr({
enableTime: false,
dateFormat: "d/M/Y",
defaultDate: new Date().fp_incr(2),
minDate: new Date().fp_incr(2),
maxDate: new Date().fp_incr(90),
disable:
function (date) {
var DisabledDates = #Html.Raw(Json.Encode(ViewBag.DisabledDates));
var array = [];
$.each(DisabledDates, function (index, value) {
var date1 = new Date(value * 1000).toDateString();
alert(index + ": " + date1);
array.push(date1);
});
var fulldmy = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
if ($.inArray(fulldmy, array) === -1) {
return false;
} else {
return true;
}
},
});
DisabledDates array in the browser debugger
function (date) {
var DisabledDates = ["\/Date(1599166800000)\/","\/Date(1599253200000)\/","\/Date(1599944400000)\/"];
var array = [];
then I tried using JsonResult action with an ajax method and the plugin stopped working again.
$("#datepicker").flatpickr({
enableTime: false,
dateFormat: "d/M/Y",
defaultDate: new Date().fp_incr(2),
minDate: new Date().fp_incr(2),
maxDate: new Date().fp_incr(90),
disable: function (date) {
$.ajax({
url: '#Url.Action("GetReservedDates", "Basket")',
type: "GET",
success: function (result) {
var fulldate = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
if ($.inArray(fulldate, result) === -1) {
return false;
} else {
return true;
}
}
});
}
});
the JsonResult action
[HttpGet]
public JsonResult GetReservedDates()
{
var dates = orderService.DisablingDates();
return Json(new { dates }, "text/x-json", JsonRequestBehavior.AllowGet);
}
this is the second plugin I'm currently tring.
What should I do?
Thanks in advance.
I found what made the plugin stop working .. the disable option takes a function between array brackets [].
then to convert the timestamp dates to readable dates I edited the value to contain only milliseconds from /Date(1599166800000)/ to 1599166800000.
finally, the plugin disabled the database-retrieved dates as intended.
$("#datepicker").flatpickr({
enableTime: false,
dateFormat: "d/M/Y",
defaultDate: new Date().fp_incr(2),
minDate: new Date().fp_incr(2),
maxDate: new Date().fp_incr(90),
disable: [Ddates],
onMonthChange: [Ddates],
});
function Ddates (date) {
var DisabledDates = #Html.Raw(Json.Encode(ViewBag.DisabledDates));
var array = [];
$.each(DisabledDates, function (index, value) {
value = value.replace("\\", "")
value = value.replace("/Date(", "")
value = value.replace(")\/", "")
var date1 = new Date(parseInt(value, 10)).toLocaleDateString();
array.push(date1);
});
date = date.toLocaleDateString();
return ($.inArray(date, array) != -1);
}

undefined from arrValue.start_date

I am trying to get from my database the start_date and end_date, however, I am getting "undefined" in console from arrValue.start_date or arrValue.(x) regardless of input.
unavailabletimes = [];
is_conflict = false
$.ajax({
url: '<%= preload_parking_path(#parking) %>',
dataTyp: 'json',
success: function(data) {
$.each(data, function(arrID, arrValue){
unavailabletimes.push([moment(moment.utc(arrValue.start_date).format('YYYY-MM-DD HH:mm')), moment(moment.utc(arrValue.end_date).format('YYYY-MM-DD HH:mm'))] );
console.log(arrValue.start_date);
})
var prestart_date = $('#reservation_start_date').datetimepicker('viewDate');
var start_date = moment(moment(prestart_date).format('YYYY-MM-DD HH:mm'));
var preend_date = $('#reservation_end_date').datetimepicker('viewDate');
var end_date = moment(moment(preend_date).format('YYYY-MM-DD HH:mm'));
if(end_date.diff(start_date, 'minutes') < 60){
var duration = 60;
}else{
if((end_date.diff(start_date, 'minutes') % 60) == 0){
var duration = end_date.diff(start_date, 'minutes');
}else{
var duration = ((end_date.diff(start_date, 'minutes') - (end_date.diff(start_date, 'minutes') % 60)) + 60);
}
}
unavailabletimes.forEach((unavailabletime)=> {
// unavailabletime = [moment, moment]
// check with start time and end time
if (start_date <= unavailabletime[0] && end_date >= unavailabletime[1]) {
is_conflict = true
}
});
if(is_conflict) {
$('#message').text("Cannot overlap existing bookings!");
$('#preview').hide();
$('#btn_book').attr('disabled', true);
} else {
var total = duration/60 * <%= #parking.price %>;
$('#message').text("");
$('#preview').show();
$('#btn_book').attr('disabled', false);
$('#reservation_hours').text(duration/60);
$('#reservation_total').text(total);
}
}
});
arrValue on itself works and it returns the database entries but adding the .(x) i.e start_date or end_date.
This is my console for arrValue
What could be the cause of this? What I am trying to do is setup a booking system that does not allow overlapped booking down to the hour. I am trying to retrieve the time interval between start_date and end_date. Push it into unavailabletimes to find conflict. I am new to coding so I apologize if its a little messy.

How to filter JSON data by datepicker in Javascript?

Hello I am a newbie programmer.
I want to get data from my API with datepicker filter.This is my API URL:https://gmlews.com/api/data/?node_id=1
First, I choose the date that I want from my datepicker. And then the data will be displayed with console.log() command.
I know how to display all data, but I don't know how to display filtered data from datepicker. The filter that I made in my code doesn't work. I think my code is wrong. This is my first code: https://jsfiddle.net/estri012/2x3hmaLo/56/
$(function() {
$('input[name="datefilter"]').daterangepicker({
showDropdowns: true,
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
}
});
$('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
var fromDate = picker.startDate.format('YYYY-MM-DD');
var toDate = picker.endDate.format('YYYY-MM-DD');
if (fromDate != '' && toDate != '') {
console.log(fromDate, toDate);
var endpoint = 'https://gmlews.com/api/data/?node_id=1';
$.ajax({
method: "GET",
url: endpoint,
data: {
fromDate: fromDate,
toDate: toDate
},
success: function(data) {
console.log(data);
var resultData = data.filter(function (a) {
var hitDates = a.timestamp || {};
// extract all date strings
hitDates = Object.keys(hitDates);
var hitDateMatchExists = hitDates.some(function(dateStr) {
var date = new Date(dateStr);
return date >= fromDate && date <= toDate
});
return hitDateMatchExists;
});
console.log(resultData);
} //function(data)end
}); //ajax end
} //if function end
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
}); //apply button end
}); //function end
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<ol class="breadcrumb">data from date : <input type="text" name="datefilter" value="" /></ol>
For example, I want to display all the data from 7 May until 8 May. So first, I pick 7 May to 8 May from my datepicker and then click apply. After I click apply, in the inspect element should show the data from 7 May until 8 May.
Can someone help me fix this code? Thankyou.
It solved! I am using plugin underscore.js. This is my final code: https://jsfiddle.net/estri012/2x3hmaLo/71/
$(function() {
$('input[name="datefilter"]').daterangepicker({
showDropdowns : true,
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
}
});
$('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
var startDate = picker.startDate.format('YYYY-MM-DD');
var endDate = picker.endDate.format('YYYY-MM-DD');
if (startDate != '' && endDate != '') {
console.log(startDate, endDate);
var endpoint = 'https://gmlews.com/api/data/?node_id=1';
$.ajax({
method: "GET",
url: endpoint,
data: {
startDate: startDate,
endDate: endDate
},
success: function(data){
var data = data;
var filteredDates = _.filter(data, function(data){
return (data.timestamp > startDate &&
data.timestamp < endDate)
});
console.log(filteredDates);
} //function(data)end
}); //ajax end
} //if function end
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
}); //apply button end
}); //function end

How to disable dates in datepicker form database?

<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "dates.php",
success: function(data) {
var obj = $.parseJSON(data);
var date = '"'
$.each(obj, function() {
date = date + this['date'] + '","';
});
date = date + '"';
$(document).ready(function() {
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: checkAvailability,
});
});
var $myBadDates = new Array(date);
function checkAvailability(mydate){
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('yy-mm-dd', mydate);
for(var i = 0; i < $myBadDates.length; i++)
{
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
return [$return,$returnclass];
}
}
});
});
</script>
This is my existing code. I just want to disable some dates in datepicker coming from database.
$myBadDates takes array of dates like this "2017-05-01", "2017-05-02" which is coming in var date. But for some reason it is not working. When I put hand-written dates in $myBadDates it works well, but with var date it is not working.
I am unable to understand what is happening here as I am new to JavaScript and JSON.
Changing one array into another is done using Array.prototype.map:
var result = input.map(function(e) { return e.date; });
ES6:
var result = input.map(e => e.date);
var input = [{"date":"2017-05-01"},{"date":"2017-04-10"},{"date":"2017-05-02"},{"date":"2017-04-30"},{"date":"2017-04-29"},{"date":"2017-04-28"},{"date":"2017-04-27"},{"date":"2017-04-26"},{"date":"2017-04-25"},{"date":"2017-04-24"},{"date":"2017-04-23"},{"date":"2017-04-14"},{"date":"2017-04-20"},{"date":"2017-05-03"},{"date":"2017-04-22"},{"date":"2017-04-21"},{"date":"2017-05-04"},{"date":"2017-04-19"},{"date":"2017-04-18"},{"date":"2017-04-17"},{"date":"2017-04-16"},{"date":"2017-04-11"},{"date":"2017-04-15"},{"date":"2017-05-05"},{"date":"2017-04-13"},{"date":"2017-04-12"},{"date":"2017-04-09"},{"date":"2017-04-08"},{"date":"2017-04-07"},{"date":"2017-04-06"},{"date":"2017-04-05"},{"date":"2017-04-04"},{"date":"2017-04-03"},{"date":"2017-04-02"},{"date":"2017-04-01"},{"date":"2017-03-31"},{"date":"2017-03-30"},{"date":"2017-02-07"},{"date":"2017-03-29"},{"date":"2017-03-28"},{"date":"2017-03-27"},{"date":"2017-02-08"},{"date":"2017-03-26"},{"date":"2017-03-25"},{"date":"2017-03-24"},{"date":"2017-03-23"},{"date":"2017-03-22"},{"date":"2017-03-21"},{"date":"2017-03-20"},{"date":"2017-02-28"}];
var output = input.map(function(e){ return e.date; });
console.log(output);

Categories

Resources