I'm having a bit of an issue with jQuery UI Datepicker where I am trying to highlight free days in a given month as determined by an ajax call.
The problem is two-fold -
The beforeShowDay only appears to be executing correctly in Chrome, not FF or IE, the free-day class is simply not being added in those browsers.
Even in Chrome, when scrolling to the previous month, the free day class is not added until returning to that month, in other words the free days are not highlighted on the first view of that month. This does not appear to be an issue moving forward a month though.
javascript
// declare freeDays global
var freeDays = [];
// perform initial json request for free days
fetchFreeDays();
$(document).ready(function()
{
// fairly standard configuration, importantly containing beforeShowDay and onChangeMonthYear custom methods
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
showOtherMonths: true,
selectOtherMonths: true,
dateFormat: 'DD, d MM, yy',
altField: '#date_due',
altFormat: 'yy-mm-dd',
beforeShowDay: highlightDays,
onChangeMonthYear: fetchFreeDays,
firstDay: 1 // rows starts on Monday
});
});
// query for free days in datepicker
function fetchFreeDays(year, month)
{
var start_date = '';
// if a month and year were supplied, build a start_date in yyyy-mm-dd format
if (year != undefined && month != undefined) {
start_date = year +'-';
start_date += month +'-';
start_date += '01';
}
$.getJSON("ajax.todos.php?start_date="+ start_date, function(data){
$.each(data, function(index, value) {
freeDays.push(value.freeDate); // add this date to the freeDays array
});
});
}
// runs for every day displayed in datepicker, adds class and tooltip if matched to days in freeDays array
function highlightDays(date)
{
for (var i = 0; i < freeDays.length; i++) {
if (new Date(freeDays[i]).toString() == date.toString()) {
return [true, 'free-day', 'no to-do items due']; // [0] = true | false if this day is selectable, [1] = class to add, [2] = tooltip to display
}
}
return [true, ''];
}
php
// ajax.todos.php
$i = 0; // counter prevents infinite loop
$cutoff = '61'; // limit on timespan (in days)
$result = array();
// if date is provided, use it, otherwise default to today
$start_date = (!empty($start_date)) ? mysql_real_escape_string($start_date) : date('Y-m-d');
$check_date = $start_date;
$end_date = date('Y-m-d', strtotime("$start_date +$cutoff days")); // never retrieve more than 2 months
while ($check_date != $end_date)
{
// check if any incomplete todos exist on this date
if (mysql_result(mysql_query("SELECT COUNT(id) FROM " . DB_TODOS . " WHERE date_due = '$check_date'"), 0) == 0)
{
$result[] = array('freeDate' => $check_date);
}
// +1 day to the check date
$check_date = date('Y-m-d', strtotime("$check_date +1 day"));
// break from loop if its looking like an infinite loop
$i++;
if ($i > $cutoff) break;
}
header('Content-type: application/json');
echo json_encode($result);
css
/* override free days background in jquery ui datepicker */
.free-day {
background: #2e9500;
}
.free-day a {
opacity: 0.7;
}
I wrote a tutorial about this a couple of months ago which is might have some extra info, which is here.
The problem is that fetchFreeDays() is asynchronous, so it is possible that $("#datepicker").datepicker() finished executeing before you have populated your freeDays array, therefore you don't see anything when the page first renders.
Try putting $("#datepicker").datepicker() inside your $.getJSONs callback function.
Related
I've created a datepicker for one of my client.
They are in a flower delivery business and they offer same day delivery for order which is placed before 12 noon. so I created a following code for that. The basic overview of its functionality is:
-> Disable current date if the time is greater than 12:00 (noon) so that customer can not put order for same day delivery.
But somehow recently one order can at 6PM for same day delivery. Which is an issue.
This is what I did so far:
<?php
// This is how i check for current date and time and if the delivery cut off time is passed add that date to disabled dates array. so customer can not put order of the current date.
current_day = date( "w" );
$todays_cut_off_time = get_option("weekday_cut_off_time_$current_day");
$todays_cut_off_time = strtotime($todays_cut_off_time);
$current_time = date( 'H:i', current_time( 'timestamp', 0 ) );
$current_time = strtotime($current_time);
if($todays_cut_off_time < $current_time)
{
$disabled_dates_array[] = date("m/d/Y");
}
?>
<script>
jQuery( document ).ready(function() {
var disableddates = <?php echo $disabled_delivery_dates; ?>; //contains list of disabled dates by admin.
exceptions = <?php echo $holiday_exception_dates; ?>; //contains dates those are exceptional
function DisableSpecificDates(date) {
var m = date.getMonth() + 1;
if(m <= 9)
m = '0'+m;
var d = date.getDate();
if(d <= 9)
d = '0'+d;
var y = date.getFullYear();
// First convert the date in to the mm-dd-yyyy format
// Take note that we will increment the month count by 1
var currentdate = m + '/' + d + '/' + y ;
// We will now check if the date belongs to exceptions array
for (var i = 0; i < exceptions.length; i++) {
// Now check if the current date is in disabled dates array.
if (jQuery.inArray(currentdate, exceptions) != -1 ) {
return [true];
}
}
// We will now check if the date belongs to disableddates array
for (var i = 0; i < disableddates.length; i++) {
// Now check if the current date is in disabled dates array.
if (jQuery.inArray(currentdate, disableddates) != -1 ) {
return [false];
}
}
// In case the date is not present in disabled array, we will now check if it is a weekend.
// We will use the noWeekends function
//var weekenddate = jQuery.datepicker.noWeekends(date);
var day = date.getDay();
return [(<?php echo $disabled_week_day; ?>), ''];
}
function FindMinDate(date){
return 0;
}
jQuery( "#delivery_date" ).datepicker({
dateFormat: 'mm-dd-yy',
minDate: 0,
beforeShowDay: DisableSpecificDates
});
});
</script>
Can somebody please guide me in the right direction to get this done. Thanks in advance.
So I have this widget on my Yii _form.php page.
Is it possible to do things like blocking a certain day of the month? Or maybe blocking all the Mondays of the Month, disallowing users to select any Monday.
UPDATES based on hamed's answer
<script type="text/javascript">
function disableSpecificDays(date) {
//date is an instance of Date
var weekDay = date.getDay(); // Get the weekday as a number (0-6)
if(weekDay == 1){ //weekDay == 1 means Monday
return false;
}
else {
return true;
}
}
</script>
And on the view side,
<?php $form->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'attribute' => 'date',
'value' => $model->date,
'options' => array(
'showAnim'=>'fadeIn',
'showButtonPanel' => true,
'minDate'=>'0',
'changeYear' => true,
'dateFormat' => 'yy-mm-dd',
'beforeShowDay' => 'disableSpecificDays',
),
));
?>
But for some reason, it blocks EVERYTHING on the date picker. Nothing can be chosen at all. At which point did I do wrong? Please advise.
jqueryUi datepicker has beforeShowDay event. You can use this event in this way:
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
...
'options'=>array(
'showAnim'=>'slide',//'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
'showOtherMonths'=>true,// Show Other month in jquery
'selectOtherMonths'=>true,// Select Other month in jquery,
'beforeShowDay' => 'disableSpecificDays', //changed ':' to '=>' AND added quote in between function name.
),
'htmlOptions'=>array(
'style'=>''
),
));
?>
Now, you need to define disableSpecificDays function inside <script> tag:
function disableSpecificDays(date) {
//date is an instance of Date
var weekDay = date.getDay(); // Get the weekday as a number (0-6)
var monthDay = date.getDate() //Get the day as a number (1-31)
if(monthDay == 12 || monthDay == 13 || weekDay == 1) //weekDay == 1 means Monday
return false;
else return true;
}
This will disable 12th an 13th days in each month and also disable Mondays.
Here are the two useful link:
jqueryUi datePicker api
javascript Date methods
I know this is an old entry but i found that for Yii 1, putting the return value inside brackets [] does the job. So the JS function should be:
<script type="text/javascript">
//DON'T SHOW SUNDAYS
function disableSpecificDays(date) {
//date is an instance of Date
var weekDay = date.getDay(); // Get the weekday as a number (0-6)
var monthDay = date.getDate();
if(weekDay == 0){
return [false];
}
else {
return [true];
}
}
</script>
This is bit legacy issue, but this is the code I made pass:
...
'options'=>array(
'beforeShowDay'=> 'js:function(date){
var weekDay = date.getDay();
var monthDay = date.getDate()
if(monthDay == 27 || weekDay == 1) { //Disable all Mondays & 27th of the each month
return [false];
} else {
return [true];
}',
...
I am implementing jquery fullcalendar in my php website. i want to make multiple selection for date. After selecting multiple dates automatically jump to agendaDay view Where i can select different time. please help me to solve this issue.Please someone tell me is it possible to select multiple dates in month view , after selecting it will jump to agendaDay view. I need end date in agendaday view so that i can add it in database. Suppose i am seleting dates from "03-02-2015" to "07-02-2015" in month view. after selecting it is jumping to day view where it is giving only "03-02-2015". not displaying "07-02-2015". i need this end date to add in my database so that i can define my schedule is from 3 feb to 7 feb.
This is my code for jump from month to day view
select: function(start, end, jsEvent, view) {
if (view.name=='month') {
var d = new Date();
var month = new Array();
month[0] = "01";
month[1] = "02";
month[2] = "03";
month[3] = "04";
month[4] = "05";
month[5] = "06";
month[6] = "07";
month[7] = "08";
month[8] = "09";
month[9] = "10";
month[10] = "11";
month[11] = "12";
var curr_date = d.getDate();
var curr_month = month[d.getMonth()];
var curr_year = d.getFullYear();
if (curr_date < 10) {
curr_date = "0" + curr_date;
}
var curdate = curr_year + '-' + curr_month + '-' + curr_date;
if(start.format() < curdate)
{
alert('You cannot fix schedule for past date');
}
else
{
$('#calendar').fullCalendar('changeView', 'agendaDay');
$('#calendar').fullCalendar('gotoDate', start, end);
}
} else {
var start = start.format();
var end = end.format();
fee_add("Today Schedule",start, end);
}
},
Display date range on multi-day event in agendaDay view
Using the eventRender callback, you can fully customize how events are displayed.
eventRender: function (event, element, view ) {
if(view.name == 'agendaDay'){ // If day view
element.find('.fc-time').remove(); // Remove the original time element
element.prepend( // Add start and end
"<span>" + event.start.format('MMM D') + // Format however you want
"-</span><span>" + event.end.format('MMM D') + "</span>");
}
},
And your select function is needlessly complicated. Make use of the fact that all dates in fullcalendar are momentjs objects.
select: function (start, end, jsEvent, view) {
if (view.name == 'month') {
if (start.isBefore(moment())) { // moment() creates a date object with the current date
alert('You cannot fix schedule for past date');
return;
} else {
$('#calendar').fullCalendar('changeView', 'agendaDay');
$('#calendar').fullCalendar('gotoDate', start, end);
}
}
$('#calendar').fullCalendar('addEventSource', [{ // This might be different for you
// but you need to actually add the new event somehow
title: "new event",
start: start,
end: end
}]);
}
And here is a working JSFiddle.
I've been trying to create a validation for my form. I've been looking around on how to disable weekends in date time picker as well as holidays. I am using this Jquery script from Trentrichardson http://trentrichardson.com/examples/timepicker/
I am sort of new in JS and am about to pull out my hair as I cannot find a way to make this code work:
$(document).ready(function(){
$('.timepicker').datetimepicker({ beforeShowDay: $.datepicker.noWeekends });
var natDays = [
[2, 26, 'ph'], [2, 6, 'ph'], [2, 17, 'ph']
];
function noWeekendsOrHolidays(date) {
var noWeekend = $.datepicker.noWeekends(date);
if (noWeekend[0]) {
return nationalDays(date);
} else {
return noWeekend;
}
}
function nationalDays(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == natDays[i][0] - 1
&& date.getDate() == natDays[i][1]) {
return [false, natDays[i][2] + '_day'];
}
}
return [true, ''];
}
});
I found this code yesterday, which is the correct answer(Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?), but I can't get it to work. It doesn't show the holidays but weekends have been disabled(working).
Any ideas?
Checking whether a date is a Saturday or Sunday should not require a separate function:
if (date.getDay() % 6) {
// date is not a weekend
} else {
// date is a weekend
}
Checking for public holidays (which can be much more difficult given that dates change from year to year and place to place) can be easy too. Create a list of the dates in a set format (ISO8601 is convenient), then you can just test against current date:
// You may have a function like this already
// d is a javascript Date object
function dateToISO(d) {
function z(n){return (n<10? '0':'')+n}
return d.getFullYear() + '-' +
z(d.getMonth() + 1) + '-' +
z(d.getDate());
}
// s is a date string in ISO8601 format
function isPublicHoliday(s) {
var holidays = '2012-12-25 2012-12-26'; // list holidays
var m = holidays.match(s);
return !!(m && m.length);
}
isPublicHoliday(dateToISO(date)); // true for 2012-12-25
Of course you will want to implement the above differently, but it gives you the gist of it. Presumably the date picker returns a date object, or a formatted string that you can test. Testing against a string is very fast and saves a lot of hassle with arrays and functions. Very easy to maintain too, since the dates are quite human readable.
For example, I select March 2013 month and I want to print the all dates of Sunday in this month. How can I print a specific day's date in month using jquery or php?
jQuery(function () {
jQuery("#datepicker").datepicker({
dateFormat: 'dd-mm-yy'
});
var day = new Date();
var month = day.getMonth() + 1;
var date = day.getDate() + '-' + month + '-' + day.getFullYear();
jQuery("#datepicker").val(da`enter code here`te);
});
I don't fully know what you mean, does this do what you want?
http://jqueryui.com/datepicker/
try this:
var date= new Date();
var month = date.getMonth() + 1;
var tmp;
var day = 1000 * 3600 * 24;
while(true) {
date = new Date(date.getTime() + day);
tmp = date.getMonth() + 1;
if(tmp!= month) {
break;
}
if(date.getDay() == 0)
document.write(date+"</br>");
}
see it work here
To do this I would find the first weekday of the month, and then find the first Sunday from that, then increment by 7 to find the rest of the Sundays.
An example in PHP:
$start = \DateTime::createFromFormat('d. m. Y', '01. 03. 2013');
$end = clone $start;
$end->add(new \DateInterval('P1M'));
// output all sundays between $start and $end
$periodInterval = \DateInterval::createFromDateString('first sunday');
$periodIterator = new \DatePeriod($start, $periodInterval, $end, \DatePeriod::EXCLUDE_START_DATE);
foreach ($periodIterator as $date) {
// output each date in the period
echo $date->format('d/m/Y') . ' ';
}
As far as you are using datepicker you may try to check every last box in the table, shown as calendar. It is gonna be the way when u will be sure that you have same data in javascript/php and on the screen