jQuery Datepicker - Multiple instances and disable previously selected dates? - javascript

I have a page where the user can select three different appointment days using the jQuery UI Datepicker. When the user selects a day in the first field, I would like that date blocked out from the other two fields. I currently am also disabling Sundays, but cannot get dynamic date disabling working.
Appointment Time 1<br />
<input id="appointment1_date" type="text" name="appointment1_date" value="Select..." />
Appointment Time 2<br />
<input id="appointment2_date" type="text" name="appointment2_date" value="Select..." />
Appointment Time 3<br />
<input id="appointment3_date" type="text" name="appointment3_date" value="Select..." />
<script type="text/javascript">
function noSunday(date){
var day = date.getDay();
return [(day > 0), ''];
};
</script>
<script type="text/javascript">
$(function() {
$("#appointment1_date").datepicker(
{
minDate: +2,
beforeShowDay: noSunday
});
});
$(function() {
$("#appointment2_date").datepicker(
{
minDate: +2,
beforeShowDay: noSunday
});
});
$(function() {
$("#appointment3_date").datepicker(
{
minDate: +2,
beforeShowDay: noSunday
});
});
</script>

You can use the beforeShowDay function to set disabled dates.
See here for a full explanation.

To block out dates from the other fields, you have to obtain the date and do the comparison in your handling function. Given the code you provided, the following should work as a replacement for noSunday:
function noSunday(date) {
var day = date.getDay();
return [
(day > 0 &&
date.valueOf() != $('#appointment1_date').datepicker('getDate').valueOf()
),
''
];
};
Basically, not only do you want to make sure that day > 0 so that it isn't a Sunday, but also make sure that the date is not equal to the date given by appointment1_date. Using .datepicker('getDate') and comparing its valueOf() with date is the key.
You might want to rename it something like noSundayOrSelected or something equally descriptive.

Related

Bootstrap Datepicker With Daterange Not Saving Value as the Specified Format

I have a booking form that requires two dates, so I'm using the built in option that Bootstrap datepicker has (it consists on calling the datepicker function on the father element that contains the inputs), to show the daterange selected, this is my HTML:
<div class="grupo vip-fechas input-daterange">
<div class="barra verde"> <span>¿Cuándo llegas?</span></div>
<input type="text" class="input calendario" id="entrada_input" name="entrada_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_inicio" name="fecha_inicio">
<div class="barra verde"> <span>¿Cuándo te vas?</span></div>
<input type="text" class="input calendario" id="salida_input" name="salida_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_fin" name="fecha_fin">
</div>
This is my Javascript code:
$(document).ready(function(){
iniciarFechas();
});
function iniciarFechas(){
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var date_hidden;
$('.vip-fechas.input-daterange').datepicker({
weekStart: 1,
maxViewMode: 1,
language: "es",
startDate: today,
disableTouchKeyboard: true,
format: {
toDisplay: function(date, format, language) {
var fecha = moment(date).add(1,"day");
date_hidden = fecha;
return fecha.format("dddd DD [de] MMMM, YYYY");
},
toValue: function(date, format, language) {
var fecha = moment(date).add(1,"day");
return moment(fecha).format("DD/MM/YY");
//return moment(date, ["DD.MM.YYYY", "DDMMYYYY"]).toDate();
}
},
}).on("changeDate", function(e){
var fecha_formateada = moment(date_hidden).format("DD/MM/YY");
$(this).next().val(fecha_formateada);
});
}
The daterange works correctly but I want to store the formatted date inside the hidden inputs, as you can see, the format that I want is this: ...format("DD/MM/YY"); but what I get is the display format: format("dddd DD [de] MMMM, YYYY"), also I noticed that $(this) value within this line: $(this).next().val(fecha_formateada); refers to the container div, and not the input that has changed value, so how can I save the date as I want inside the hidden inputs?
I'm not sure what your problem is but by looking at your code I can only guess that you might be in the middle of a race condition.
You're setting the date_hidden variable in Datepicker.toDisplay and then reading from it in the changeDate custom event.
Put a debugger or a console log in both callbacks to make sure you're not in the middle of a race condition.
As for setting the formatted value in the input fields, well I can see in your HTML code that you have selectors that you can use, like the hidden field's ID for example.
Another thing I'd suggest is, instead of setting and reading the date_hidden field in those different callbacks, just call $('#elementID').datepicker('getDate') in the changeDate event handler and do all the transformations you need there, then extract that code and put it in a separate function.

Jquery UI Datepicker Show Additional Disabled Dates

I am trying to show additional disabled dates for the datepicker. For instance, I have min date as 2-1-2018 and max date as 3-1-2018. Is there anyway way to show 1-1-2018 and 4-1-2018 as disabled? Here is what I have right now. I don't need to dynamically set the dates. I need to display additional disabled dates so the user can see a larger range of disabled dates.
beforeShow : function () {
if (attrs.selecteddate) {
/*
2018-10-29T00:00:00.000+0000 before
2018-10-29 after
Only need the 00-00-0000 part of the date to avoid time zone issues. QoT always returns 00T for timezone anyways.
*/
var formattedDate = attrs.selecteddate.split("T");
attrs["formattedDate"] = formattedDate[0].substring(5) + "-" + formattedDate[0].substring(0, 4);
/*z
Set the date that the calander will display.
Append universal date time zone so correct date will be set in Firefox. It replaces T00:00:00.000+0000 with T12:00:00Z
*/
jQuery(this).datepicker('setDate', new Date(formattedDate[0] + 'T12:00:00Z'));
}
jQuery(this).datepicker('option', {
minDate : ( attrs.edittype === 'single' ) ? incrementDate(attrs.mindate) : attrs.mindate,
maxDate : ( attrs.edittype === 'single' ) ? convertToDateObj(attrs.maxdate) : attrs.maxdate
});
},
This below js code will help you to change min and max date dynamically.
$(function(){
$("#fdate").datepicker({
formatDate:"dd-mm-yy",
onselect:function(){
//do stuff here
},
onclose:function(){
//do stuff here
}
});
var date1 = "15-11-2017";
var date2 = "17-11-2017"; //you can pass dynamically date
$("#fdate").datepicker("option", "minDate", date1);
$("#fdate").datepicker("option", "maxDate", date2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.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>
<input id="fdate" type="text" name="date" />

If datepicker already has value run onselect anyway

Currently, I can select a date and it fills my input fields with the date for 7 days and the corresponding day of the week in another series on input fields (just 3 days in example below). This is working well, although I'm sure there is a more efficient way to write the same thing with arrays, I just have no idea.
However, if I get the start date from the database on page load rather than selecting it with datepicker, it obviously doesn't trigger the onselect event and the fields don't populate. How can I get it to populate the fields in both situations?
I was thinking a function that is run when either the datepicker input has a valid value or onselect, but having never really touched JS before this little project I'm in over my head.
$(function() {
$("#StartDate").datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function(dateStr, inst) {
var weekday=new Array(7);
weekday[0]="Monday";
weekday[1]="Tuesday";
weekday[2]="Wednesday";
weekday[3]="Thursday";
weekday[4]="Friday";
weekday[5]="Saturday";
weekday[6]="Sunday";
var Date1 = $.datepicker.parseDate('dd/mm/yy', dateStr);
Date1.setDate(Date1.getDate('dd/mm/yy'));
$('#Date1').val(Date1.toLocaleDateString());
$('#Day1').val(weekday[Date1.getUTCDay()]);
var Date2 = $.datepicker.parseDate('dd/mm/yy', dateStr);
Date2.setDate(Date2.getDate('dd/mm/yy') + 1);
$('#Date2').val(Date2.toLocaleDateString());
$('#Day2').val(weekday[Date2.getUTCDay()]);
var Date3 = $.datepicker.parseDate('dd/mm/yy', dateStr);
Date3.setDate(Date3.getDate('dd/mm/yy') + 2);
$('#Date3').val(Date3.toLocaleDateString());
$('#Day3').val(weekday[Date3.getUTCDay()]);
}
});
});
What about a loop like this?
$(function() {
$("#StartDate").datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function(dateStr, inst) {
var weekday=new Array(7);
weekday[0]="Monday";
weekday[1]="Tuesday";
weekday[2]="Wednesday";
weekday[3]="Thursday";
weekday[4]="Friday";
weekday[5]="Saturday";
weekday[6]="Sunday";
for(i=0;i<weekday.length;i++){
var Date = $.datepicker.parseDate('dd/mm/yy', dateStr);
Date.setDate(Date.getDate('dd/mm/yy') + i); // "i" is the array index
$('#Date').val(Date.toLocaleDateString());
$('#Day').val(weekday[Date.getUTCDay()]);
}
});
});
EDIT --- I misunderstood the question.
So here is another try, since I'm still unsure to get it... But getting closer.
If #startDate is already populated onload, you wish to run the above script as if it was selected using the datepicker, right?
So assuming something like this, on PHP side, to fill the StartDate field:
<input type="text" id="startDate" value="<?php echo $date; ?>"></input>
I would get this function out of the datepicker init to be able to run it from elsewhere.
I've done a CodePen to test this.
// This is the function you had on select
var DayFill = function(dateStr, inst) {
var weekday=new Array(7);
weekday[0]="Monday";
weekday[1]="Tuesday";
weekday[2]="Wednesday";
weekday[3]="Thursday";
weekday[4]="Friday";
weekday[5]="Saturday";
weekday[6]="Sunday";
for(i=0;i<weekday.length;i++){
var Date = $.datepicker.parseDate('dd/mm/yy', dateStr);
Date.setDate(Date.getDate('dd/mm/yy') + i); // "i" is the array index
$('#Date'+i).val(Date.toLocaleDateString());
// Fix day number to fit the array index
var daynum = Date.getUTCDay()-1;
if(daynum==-1){
daynum=6;
}
$('#Day'+i).val(weekday[daynum]);
}
}
// This is your datepicker init
$("#StartDate").datepicker({
dateFormat: 'dd/mm/yy',
onSelect: DayFill // Call the FillDay function, now out of this init.
});
// Onload, run the DayFill function using the input value
$(document).ready(function(){
DayFill( $("#StartDate").val() );
});

Date Picker Highlight day if not Available

I have this online reservation, and i have this problem, Is there a way i can highlight the unavailable days on the date picker?assuming i have inserted dates on the database. Here's my code for the date picker.
<input type="text" name="pick-up-date" id="pick-up-date" class="form-control datepicker" placeholder="mm-dd-yyyy">
Here's a screenshot:
Use beforeShowDay() function from jQuery check this
e.g., something like this,
var datesToDisable = ["2015-01-07","2015-17-07","2015-21-07"]; //you have to fetch the dates and put em in an array and wh7atever the format is.
$('#pick-up-date').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [ datesToDisable.indexOf(string) == -1 ]
}
});
Should do the trick!

Validate date so that the date cannot be in future or in past

I have this form that has a date input. What is the best way in Javascript that I can ensure the value selected is neither a future date or a past date. I have implemented jQuery date picker to select date see code below
<html>
<!--maina-->
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="main.css" rel="stylesheet" type="text/css"/>
<script>
$(function() {
var date = $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
});
function ValidateForm(){
var date_of_circulation = document.forms["myForm"]["date_of_circulation"].value;
if (date_of_circulation == null || date_of_circulation ==""){
alert ("You have to select the date the manuscript was circulated");
return false;
}
}
</script>
<form enctype="multipart/form-data" name = "myForm" action = "" onsubmit="return ValidateForm()" method = "post">
Date of circulation:<input name="date_of_circulation" input type="text" id="datepicker"></p>
<input name = "add_manuscript" type="submit" value = "submit">
</form>
</html>
You can do it like this
var yourDate = new Date("12/5/2015"); //input value
var todayDate = new Date(); //Gets the today's date value
You have to use function setHours
if(yourDate.setHours(0,0,0,0) == todayDate.setHours(0,0,0,0));
{
//Do your stuff
}
NOTE: You can also do it using the jquery's datepicker
var currentDate = new Date();
$("#datepicker").datepicker("setDate", currentDate);
so that you can be sure that today's date is already selected.
EDIT: You can also look at datejs
datejs API Documentation
i found an effective and simple solution by introducing maxdate and mindate as explained here: date picker restrict date range. After rethinking the validation rules i decided that the logical validation for date_of_circulation value can be a date in the past but not exceeding current date and therefore changed var date in date picker to
var date = $("#datepicker").datepicker({ maxDate: new Date,dateFormat: 'yy-mm-dd', minDate: new Date (0) });
If date field must be set as current date, no future or past date than
set text field's default value to current date, you need not to use date picker as it's not user friendly to have a date picker without any other date option.
Also by doing this way, you need not to validate form on submit.
<input name="date_of_circulation" input type="text" id="datepicker" value="<?php echo date('Y-m-d'); ?>" readonly="readonly">
set input box as readonly so that user can not change the date.

Categories

Resources