Datepicker onchangemonthyear beforeshowday - javascript

I have the datepicker on a modal of twitter bootstrap.
in order to highlight some dates, the datepicker is generated in the 'success'-part as an ajax-call.
I manage to highlight the dates I want to highlight in the current month, which is fine.
But when I toggle to the previous or next month, I would like to make that ajax-call again and render dates to highlight. Below you can see my code:
function nonValidated() {
var date = new Date();
date.addDays(-date.getDate() + 1);
var startDate = [date.getDate().lpad(2), (date.getMonth() + 1).lpad(2), date.getFullYear()].join('/');
var enddate = new Date();
enddate.setDate(date.getDaysInMonth());
var endDate = [enddate.getDate().lpad(2), (enddate.getMonth() + 1).lpad(2), enddate.getFullYear()].join('/');
var depId = $('#serviceSelector').val();
$.ajax({
type: "POST",
url: "/ServiceManagement/GetUnassignedSlots",
data: { "from": startDate, "to": endDate, "depId": depId },
success: function (data) {
$.datepicker.setDefaults(
$.extend(
{ 'dateFormat': 'dd/mm/yy' },
$.datepicker.regional['nl-BE']
)
);
$("#nonValidatedDatepicker").datepicker(
{
inline: true,
beforeShowDay: function (date) {
var theday = date.getDate() + '/' +
(date.getMonth() + 1).lpad(2) + '/' +
date.getFullYear();
return [true, $.inArray(theday, data.result) >= 0 ? "warningDate" : ''];
},
onSelect: function (dateText, inst) {
var dateParts = dateText.split('/');
if (dateParts[0][0] == '0') dateParts[0] = dateParts[0][1];
if (dateParts[1][0] == '0') dateParts[1] = dateParts[1][1];
var newdate = new Date(dateParts[2], dateParts[0]-1, dateParts[1]);
var dayOfWeek = newdate.getDay();
if (dayOfWeek == 0) dayOfWeek = 7;
var weekstart = new Date(newdate.getFullYear(), newdate.getMonth(), newdate.getDate());
weekstart.addDays(-dayOfWeek + 1);
var weekend = new Date(newdate.getFullYear(), newdate.getMonth(), newdate.getDate());
weekend.addDays(7 - dayOfWeek);
$('#SelectWeekDate').val([weekstart.getDate().lpad(2), (weekstart.getMonth() + 1).lpad(2), weekstart.getFullYear()].join('/') + ' - ' + [weekend.getDate().lpad(2), (weekend.getMonth() + 1).lpad(2), weekend.getFullYear()].join('/'));
$('#modalNonValidated').modal('hide');
InitFillPage();
},
onChangeMonthYear: function (year, month, widget) {
}
}
);
},
error: function (data) {
},
statusCode: {
401: function (data) {
//ERROR 401: Unauthenticated
window.location.href = '/Account/Login?ReturnUrl=' + encodeURIComponent(window.location.pathname);
}
}
});
}
anyone an idea how I can combine onchangemonthyear and beforeshowday?

I would split the code that shows the datepicker and the code that makes the ajax call to get the data for the datepicker (the data that determines which days to highlight) into 2 separate functions. You can call the function that makes the ajax call from the function that first shows the datepicker, and again from your onChangeMonthYear function. Also, make sure that the ajax call to get the data is made synchronously (set async: false option) so that the data comes back before your beforeShowDay function runs.
Hope that helps!

Related

I've got stuck with daterangepicker, Im triying to validate ranges dates, it works but Im inside a loop

This is my situation; the daterangepicker is working, everything is working indeed, but there is a loop I cant find a way to avoid. Each time I choose a date range with invalid date Ive got the alert message but this never stop popping up. In fact, I found that if I hide all the code insideisInvalidDate and I just write a console.log, there is still a loop. Ive tried to take the validaterange function outside but as the variables are locals, the function doesnt work.
This is my .js:
$(document).ready(function () {
idRoom = document.getElementById("room_name").value;
$.ajax({
url: "getData/" + idRoom,
type: "get",
dataType: "json",
success: function (response) {
var today = new Date();
var day =
today.getFullYear() +
"/" +
today.getMonth() +
+1 +
"/" +
today.getDate();
$('input[name="daterange"]').daterangepicker({
opens: "right",
drops: "up",
minDate: day,
maxSpan: {
days: 15,
},
locale: {
format: "YYYY/MM/DD",
},
isInvalidDate: function (date) {
var len = response["data"].length;
for (var i = 0; i < len; i++) {
var Str = response["data"][
i
].reservation_checkout.replace(/-/g, ","); //quitamos 1 dia al checkout para que ese dia este disponible
var newStr = new Date(Str);
newStr.setDate(newStr.getDate() - 1);
var newdate = new Date(newStr);
date[i] = newdate.toISOString().split("T")[0];
}
var dateRanges = []; //obtenemos los datos checking/checkout y los metemos en datepicker
for (var i = 0; i < len; i++) {
dateRanges.push({
start: moment(
response["data"][i].reservation_checking
),
end: moment(date[i]),
});
}
var dateRangesfix = [];
for (var i = 0; i < len; i++) {
var startDatefix = moment(
response["data"][i].reservation_checking
).format("DD-MM-YYYY");
var endDatefix = moment(
response["data"][i].reservation_checkout
).format("DD-MM-YYYY");
dateRangesfix.push(startDatefix, endDatefix);
}
$('input[name="daterange"]').on(
"apply.daterangepicker",
function validateDateRange() {
var txtStartDate = $(
'input[name="daterange"]'
).data("daterangepicker").startDate;
var txtEndDate = $('input[name="daterange"]').data(
"daterangepicker"
).endDate;
var startDate;
var endDate;
var tempDate;
if (txtStartDate == "") return false;
if (txtEndDate == "") return false;
startDate = new Date(txtStartDate);
endDate = new Date(txtEndDate);
for (i = 0; i < 2 * len; i++) {
var temp = dateRangesfix[i].split("-");
tempDate = new Date(
temp[2],
temp[1] - 1,
temp[0]
);
if (
startDate < tempDate &&
endDate > tempDate
) {
alert("Invalid Date Range");
return false;
}
}
}
);
return dateRanges.reduce(function (bool, range) {
return (
bool || (date >= range.start && date <= range.end)
);
}, false);
},
});
},
});
});
$("#button1").click(function (event) {
startDate = $('input[name="daterange"]').data("daterangepicker").startDate;
var d = new Date(startDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
start_Date_fix = year + "-" + month + "-" + day;
document.getElementById("start_Date").value = start_Date_fix;
endDate = $('input[name="daterange"]').data("daterangepicker").endDate;
var d = new Date(endDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
end_Date_fix = year + "-" + month + "-" + day;
document.getElementById("end_Date").value = end_Date_fix;
//calcular numero de noches
var date = $('input[name="daterange"]').val();
var str = date.split("-");
var startDate = str[0];
var startDate_f = startDate.split("/");
var startDate_fo = new Date(
startDate_f[0],
startDate_f[1] - 1,
startDate_f[2]
);
var endDate = str[1];
var endDate_f = endDate.split("/");
var endDate_fo = new Date(endDate_f[0], endDate_f[1] - 1, endDate_f[2]);
var Difference_In_Days = Math.round(
(endDate_fo - startDate_fo) / (1000 * 60 * 60 * 24)
);
var year = startDate_f[0];
var month = startDate_f[1];
var day = startDate_f[2].replace(/\s+/g, "");
var guests = document.getElementById("guests").value;
$.ajax({
url:
"calculatePrice/" +
year +
"/" +
month +
"/" +
day +
"/" +
Difference_In_Days +
"/" +
idRoom +
"/" +
guests,
type: "get",
dataType: "json",
data: {},
success: function (data) {
document.getElementById("total_amount").value = data;
},
});
});
I pasted a full copy but I suppose the problem should be in those lines. As youll see Im an newbie and I hope you understand my poor level of English. I've spent some time reading post but Im not really sure about this.
Thank you so much.
I've solved, Ive just been able to take the function out like this;
$(document).ready(function () {
idRoom = document.getElementById("room_name").value;
$.ajax({
url: "getData/" + idRoom,
type: "get",
dataType: "json",
success: function (response) {
var today = new Date();
var day =
today.getFullYear() +
"/" +
today.getMonth() +
+1 +
"/" +
today.getDate();
$('input[name="daterange"]').daterangepicker({
opens: "right",
drops: "up",
minDate: day,
maxSpan: {
days: 15,
},
locale: {
format: "YYYY/MM/DD",
},
isInvalidDate: function (date) {
var len = response["data"].length;
for (var i = 0; i < len; i++) {
var Str = response["data"][
i
].reservation_checkout.replace(/-/g, ","); //quitamos 1 dia al checkout para que ese dia este disponible
var newStr = new Date(Str);
newStr.setDate(newStr.getDate() - 1);
var newdate = new Date(newStr);
date[i] = newdate.toISOString().split("T")[0];
}
var dateRanges = []; //obtenemos los datos checking/checkout y los metemos en datepicker
for (var i = 0; i < len; i++) {
dateRanges.push({
start: moment(
response["data"][i].reservation_checking
),
end: moment(date[i]),
});
}
return dateRanges.reduce(function (bool, range) {
return (
bool || (date >= range.start && date <= range.end)
);
}, false);
},
});
var len = response["data"].length;
var dateRangesfix = [];
for (var i = 0; i < len; i++) {
var startDatefix = moment(
response["data"][i].reservation_checking
).format("DD-MM-YYYY");
var endDatefix = moment(
response["data"][i].reservation_checkout
).format("DD-MM-YYYY");
dateRangesfix.push(startDatefix, endDatefix);
}
$('input[name="daterange"]').on(
"apply.daterangepicker",
function validateDateRange() {
var txtStartDate = $('input[name="daterange"]').data(
"daterangepicker"
).startDate;
var txtEndDate = $('input[name="daterange"]').data(
"daterangepicker"
).endDate;
var startDate;
var endDate;
var tempDate;
if (txtStartDate == "") return false;
if (txtEndDate == "") return false;
startDate = new Date(txtStartDate);
endDate = new Date(txtEndDate);
for (i = 0; i < 2 * len; i++) {
var temp = dateRangesfix[i].split("-");
tempDate = new Date(temp[2], temp[1] - 1, temp[0]);
if (startDate < tempDate && endDate > tempDate) {
alert("Invalid Date Range");
return false;
}
}
}
);
},
});
});
$("#button1").click(function (event) {
startDate = $('input[name="daterange"]').data("daterangepicker").startDate;
var d = new Date(startDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
start_Date_fix = year + "-" + month + "-" + day;
document.getElementById("start_Date").value = start_Date_fix;
endDate = $('input[name="daterange"]').data("daterangepicker").endDate;
var d = new Date(endDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
end_Date_fix = year + "-" + month + "-" + day;
document.getElementById("end_Date").value = end_Date_fix;
//calcular numero de noches
var date = $('input[name="daterange"]').val();
var str = date.split("-");
var startDate = str[0];
var startDate_f = startDate.split("/");
var startDate_fo = new Date(
startDate_f[0],
startDate_f[1] - 1,
startDate_f[2]
);
var endDate = str[1];
var endDate_f = endDate.split("/");
var endDate_fo = new Date(endDate_f[0], endDate_f[1] - 1, endDate_f[2]);
var Difference_In_Days = Math.round(
(endDate_fo - startDate_fo) / (1000 * 60 * 60 * 24)
);
var year = startDate_f[0];
var month = startDate_f[1];
var day = startDate_f[2].replace(/\s+/g, "");
var guests = document.getElementById("guests").value;
$.ajax({
url:
"calculatePrice/" +
year +
"/" +
month +
"/" +
day +
"/" +
Difference_In_Days +
"/" +
idRoom +
"/" +
guests,
type: "get",
dataType: "json",
data: {},
success: function (data) {
document.getElementById("total_amount").value = data;
},
});
});
I would recommend validating the date ranges server-side with Laravel's Validation
tools and Carbon if formatting is required. Instead of using the GET method on the price calculator route:
$.ajax({
url:
"calculatePrice/" +
year +
"/" +
month +
"/" +
day +
"/" +
Difference_In_Days +
"/" +
idRoom +
"/" +
guests,
You would make a post request and use the Request $request typehint or Request facade to access incoming data and simply return the data from the calculator OR continue to use the GET method and pass the date input as a wildcard/route-parameter to.
If you require front-end validation, I would recommend using a Vue component and a package such as Vuelidate to simplify the process. In my experience, front-end validation is very time-consuming without using Vuelidate. This would be my recommendation, as there are plenty of date-picker Vue components available as well which can be configured to format on the front-end also.
(If by "alert" you meant an actual alert window and not a bootstrap component)
Sidenote: using Alerts to report validation errors is not practical and in my personal opinion, shouldn't be used. Instead, validate server-side and return error messages, check for error messages on the front end, and then display those messages near the input it's for.
It looks like you answered your own issue while I was typing this, so I'll leave it here anyway.

Get Date part of DateTime(ASP.NET MVC)

I have this property in Model
[Display(Name = "День рождения")]
[DataType(DataType.Date)]
public System.DateTime Birthday { get; set; }
And write to database value like this via AJAX
<script>
$(document).ready(function () {
$('#save').click(function () {
save();
});
});
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
FIO: $('#FIO').val(),
Email: $('#Email').val(),
Salary: $('#Salary').val(),
Telephone: $('#Telephone').val(),
English: $('#english').val(),
City: $('#City').val(),
Birthday: $('#Birthday').val(),
id: $('#Interview_Id').val(),
},
url: '#Url.Action("WelcomeWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
window.location.href = da.RedirectUrl;
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
But my problem is this - it is writing Date and Time , I only need Date.
How I can fix this?
You can use this:
var date = new Date($('#Birthday').val());
This will give you access to all the Date functions.
For example:
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear()
So for full date:
var fullDate=day+"/"+month+"/"+year;
Or:
var fullDate=d.toLocaleDateString();
Format your date in your save() method before you do your ajax call. Something like this:
var d = new Date($('#Birthday').val());
var birthday = d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2)
+ "-" + ('0' + d.getDate()).slice(-2);

jQuery DatePicker background color for cells where event exists (on load)

I want to change the background-color for cells where events exist.
In this case for this day: 2016-04-07
I hope someone can help me, I don't find a solution here in SO.
Thank you
JS code:
// I WANT TO CHANGE BACKGROUND-COLOR FOR THIS DAY
var events = {"2016-04-07":[{"title":"Friday!!!!","description":"Weekend is starting!!!"}]};
// Setup our datepicker
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: findEvents
});
// Provide a function to find and display events
function findEvents (date) {
// Start by emptying our data container
$("#dateevents").empty();
// Potential date object
var dateObj = events[date];
// If no events exist for the selected date
if (!dateObj) {
return $("#dateevents").html( "<h2>" + date + ": No Events</h2>" );
}
// If we've made it this far, we have events!
$("#dateevents").html( "<h2>" + date + ": " + dateObj.length + " Events Planned</h2>" );
// Cycle over every event for this date
$.each(dateObj, function (index, event) {
// Build a list for each event
var $list = $("<ul>");
// Add all event details to list
$.each(event, function (name, desc) {
$("<li>").html(name + ": " + desc).appendTo($list);
});
// Place list in container
$list.appendTo("#dateevents");
});
}
Fiddle: http://jsfiddle.net/qSCek/6/
Try something like this, looping over the html you might want to put it in a function and call it on month change etc.
// Provide some event data in JSON format
var events = {"2016-04-07":[{"title":"Friday!!!!","description":"Weekend is starting!!!"}]};
// Setup our datepicker
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: findEvents,
});
$("td[data-handler='selectDay']").each(function(index,value){
var month = $(value).attr("data-month");
var year = $(value).attr("data-year");
var day = $(value).next().text();
var date = year+"-"+(parseInt(month) + 1)+"-"+day
$.each(events, function(i, v) {
var parts = i.split("-")
parts[1] = parts[1].replace("0","")
parts[2] = parts[2].replace("0","")
var i = parts[0]+"-"+parts[1]+"-"+parts[2]
if (i == date) {
console.log("hit")
console.log(date)
$(value).next().css("background","red")
}
});
})
// Provide a function to find and display events
function findEvents (date) {
// Start by emptying our data container
$("#dateevents").empty();
// Potential date object
var dateObj = events[date];
// If no events exist for the selected date
if (!dateObj) {
return $("#dateevents").html( "<h2>" + date + ": No Events</h2>" );
}
// If we've made it this far, we have events!
$("#dateevents").html( "<h2>" + date + ": " + dateObj.length + " Events Planned</h2>" );
// Cycle over every event for this date
$.each(dateObj, function (index, event) {
// Build a list for each event
var $list = $("<ul>");
// Add all event details to list
$.each(event, function (name, desc) {
$("<li>").html(name + ": " + desc).appendTo($list);
});
// Place list in container
$list.appendTo("#dateevents");
});
}
fiddle http://jsfiddle.net/qSCek/7/
Here is what I accomplished to do. The problem I think is that the onChangeMonthYear callback is called before the view is rendered. So I put a timeout to solve the problem.
// Setup our datepicker
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: findEvents,
onChangeMonthYear: function(year, month) {
setTimeout(changeBackground, 1, year, month)
}
});
var d = new Date();
changeBackground(d.getFullYear(), d.getMonth() + 1);
function changeBackground(year, month) {
for (var date in events) {
var d = new Date(date);
// if same day and year
if (d.getFullYear() === year && d.getMonth() + 1 === month) {
var day = d.getDate();
// retrieve all elements containing day
var elements = $('a:contains(' + day + ')');
elements.each(function(index) {
if ($(this).text() == day) {
$(this).css("background", "red");
}
});
};
}
}
And here is the fiddle

Jquery UI DatePicker Restrict Set Of Date

I am working on Jquery-UI Datepicker for hotel domain project. Basically hotel have some of Packages/Offers that are not valid on some of date durations. This durations are coming from database. Between these date user can't select date for booking from Jquery-UI Calendar. I don't know how to implement this.
$(".calendar").datepicker({
dateFormat: 'dd/mm/yy',
minDate:0
});
/* an array of days which are not applicable for packages/offers Booking */
var disabledDays = ["10-25-2015","10-26-2015","10-27-2015","10-28-2015","11-3-2015","11-4-2015","11-5-2015","11-20-2015","11-21-2015","11-22-2015","12-12-2015","12-13-2015"];
/* utility functions */
function getBookedDays(date) {
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
//
}
http://jsfiddle.net/ANJYR/34yfb2zs/1/
When calendar open user can't select date from 25 Oct 2015 To 28 Oct 2015 as so on dates.
You can try like this:
$('.calendar').datepicker({
beforeShowDay: function(date){
var str = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ disabledDays.indexOf(str) == -1 ]
}
});
JSFIDDLE DEMO
$(".calendar").datepicker({
dateFormat: 'dd/mm/yy',
minDate:0,
beforeShowDay: getBookedDays
});
/* an array of days which are not applicable for packages/offers Booking */
var disabledDays = ["10-25-2015","10-26-2015","10-27-2015","10-28-2015","11-3-2015","11-4-2015","11-5-2015","11-20-2015","11-21-2015","11-22-2015","12-12-2015","12-13-2015"];
/* utility functions */
function getBookedDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y,disabledDays) != -1) {
return [false];
}
}
return [true];
}
DEMO
See demo example at: jsFiddle Example
var unavailableDates = ["28-10-2015", "29-10-2015", "27-10-2015"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
$(function() {
$("#iDate").datepicker({
defaultDate: new Date("1-10-2015"),
dateFormat: 'dd MM yy',
beforeShowDay: unavailable
});
});
Try this:
var disableddates = ["28-10-2015", "29-10-2015", "27-10-2015"];
function DisableSpecificDates(date) {
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var currentdate = (m + 1) + '-' + d + '-' + y ;
for (var i = 0; i < disableddates.length; i++) {
if ($.inArray(currentdate, disableddates) != -1 ) {
return [false];
}
}
}
$(function() {
$( ".calendar" ).datepicker({
beforeShowDay: DisableSpecificDates
});
});

datePicker in jQuery UI not working

I want to call the beforeShowDay function in jquery UI datepicker, but I found that the location
of beforeShowDay matters and I have no clue.
Code would help:
<script>
var datePickerOptions = {
minDate: 'today',
beforeShowDay: available
};
/*This is a function only let datePicker show the dates in dateList*/
var available = function(date){
window.console.log("in");
var dmy = (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear();
if($.inArray( dmy, dateList ) !== -1 ) {
return [true, "", "Available"];
}
else {
return [false, "", "unAvailable"];
}
};
var init = function(availableDates) {
$('.datePicker').datepicker(datePickerOptions);
};
</script>
If I write it in this way, the minDate would work, but the beforeShowDay wouldn't, the console didn't print 'in'.
But if I write it in this way:
var init = function(availableDates) {
$('.datePicker').datepicker({
minDate: 'today',
beforeShowDay: available
});
};
it would work.I don't see the real difference between these two methods, and I really want to use the first method.
Any ideas? Thanks.
It is because when available is used to create the datePickerOptions object it is not initialized with a value, so it has a value of undefined which is same as not passing the option in this case. You can move the creation of datePickerOptions after the available variable is initialized to fix the problem.
/*This is a function only let datePicker show the dates in dateList*/
var available = function(date){
window.console.log("in");
var dmy = (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear();
if($.inArray( dmy, dateList ) !== -1 ) {
return [true, "", "Available"];
}
else {
return [false, "", "unAvailable"];
}
};
var datePickerOptions = {
minDate: 'today',
beforeShowDay: available
};
var init = function(availableDates) {
$('.datePicker').datepicker(datePickerOptions);
};

Categories

Resources