How to disable previous days in default DHTML calendar?
I used the following code,
<script type="text/javascript">
Calendar.setup({
inputField : '_dob',
ifFormat : '%m/%e/%y',
button : '_dob_trig',
align : 'Bl',
singleClick : true,
disableFunc: function(date) {
var now= new Date();
return (date.getTime() < now.getTime());
}
});
</script>
It works in disabling the previous dates. But when we select on valid date, nothing happens. The date is not being added to the text filed of calendar.
If I changes the month and comes back , I can select date!
Any Idea?
Wow!
It might be some javascript error. I was unable to select any dates unless going and coming back from next month...
I past it by giving some if loops. My updated code is below.
<script type="text/javascript">
Calendar.setup({
inputField : '_dob',
ifFormat : '%m/%e/%y',
button : '_dob_trig',
align : 'Bl',
singleClick : true,
disableFunc: function(date) {
var now= new Date();
if(date.getFullYear()<now.getFullYear())
{
return true;
}
if(date.getFullYear()==now.getFullYear())
{
if(date.getMonth()<now.getMonth())
{
return true;
}
}
if(date.getMonth()==now.getMonth())
{
if(date.getDate()<now.getDate())
{
return true;
}
}
},
});
</script>
Greetings to everyone replied...
I had the same problem, and after debugging it, the problem seems to be that the calendar can't figure out what the current calendar date should be (because it's disabled by the disableFunc callback function). You have two options available.
Make sure the disableFunc function returns false for the current date. This way it won't be disabled in the calendar, and it'll function properly.
You can add the following lines in the calendar.js, after the if (!cell.disabled) line. (that happens to be line 1183 in my version of the file - v 1.51)
else
{
this.currentDateEl = cell;
}
The second option will allow you to disable the current date as well.
For those wondering what this DHTML calendar is, here is a link to it's docs: http://www.dni.ru/js/doc/html/reference.html
Disable Function should return TRUE or FALSE always.
disableFunc function: A function that receives a JS Date object. It should return true if that date has to be disabled, false otherwise. DEPRECATED (see below).
Please refer the following,
DHTML CALENDAR SETTINGS REFERENCE
But in your code disable function returns nothing... :( so it goes into js error and nothing works on event click..
check your condition,
return (date.getDate() <= now.getDate());
Return true or false according to your requirement after checking the above condition...
try the code below
Calendar.setup({
inputField : '_dob',
ifFormat : '%m/%e/%y',
button : '_dob_trig',
align : 'Bl',
singleClick : true,
dateStatusFunc : function (date) {
var now= new Date();
return (date.getDate() <= now.getDate());
}
});
Related
We are using the Datatables ultimate date/time sorting plugin (https://datatables.net/blog/2014-12-18) to try and sort date columns, but not having any luck getting it to properly sort dates in the right format. When the page loads, the following script is run:
//sets the date format for datatables for sorting purposes
//reference: https://datatables.net/blog/2014-12-18
$.fn.dataTable.moment( 'M/D/YYYY' );
/* Datatables */
$('.datatable').DataTable({
language : {
search : "_INPUT_",
searchPlaceholder : "Search...",
paginate : {
"next" : '<i class="fa fa-chevron-right"></i>',
"previous" : '<i class="fa fa-chevron-left"></i>'
}
},
responsive : {
details : {
display : $.fn.dataTable.Responsive.display.childRowImmediate,
type : 'column'
}
},
order : [0, 'desc'],
//date sorting
columnDefs:
{
targets: 'date_sortable',
render: function ( data, type, full, meta ) {
if(type === 'display'){
if(data){
var mDate = moment(data);
data = (mDate && mDate.isValid()) ? mDate.format("M/D/YYYY") : "";
console.log('rewrote data to ' + data);
}
}
console.log('date_sortable rendered');
return data;
}
}
});
According to both the Datatables documentation and the details I found on this SO post (DataTables Ultimate date / time sorting plug-in not working with Intl formats), I added date_sortable as a class name on the <th /> element in my HTML, but it looks like the render function isn't called, as my console.log[...] entries never run. I can see in the generated HTML the class is on my <th /> element, and the dates being shown are in the proper format ('n/j/Y', in PHP) so I'm at a total loss.
Everything looks setup correctly, so any tips/pointers here? The date ordering seems to be rather random in nature, with entries that have dates such as 1/6/2016 showing up in the middle (see screenshot), which makes no sense at all.
I will say this table is showing ~2,055 records so is it possibly a performance thing? This isn't currently loading with API calls, so all records are in the generated HTML as a single file.
can you look at the unshifted Function in Datatables?
// Add type detection
types.detect.unshift( function ( d ) {
return moment( d, format, locale, true ).isValid() ?
'moment-'+format :
null;
} );
if it's the case, you should use this:
$.fn.dataTable.moment('YYYY-M-D');
Please try this fiddle (this works with your date format):
`http://jsfiddle.net/Marouen/9qdj53am`
Hope this will help.
I have made an inline datepicker, i only got 1 issue.
I can't implement the beforeShowDay option
i use PHP to load an array out of a database. I implement this with AJAX
code:
$(document).ready(function() {
var ajax = $.ajax({
url : "dates.php",
data : "action=showdates",
dataType : "json"
});
ajax.complete(function(calendarEvents) {
$("#inline").datepicker({
beforeShowDay : ShowDay()
});
function ShowDay(date) {
console.log('function showday');
for (var i = 0; i < calendarEvents.length; i++) {
var jaar = calendarEvents[i].slice(0,4);
console.log(jaar);
}
console.log('showday');
}
});
});
the trouble i have atm is that i want to have appointment on certain days.
i would ike to use the return [true, "classname", ""] for dates with an appointment, and return [true, "", ""] for all the other dates. i hope i can get some help!
This is what i am trying to do: http://www.emirplicanic.com/javascript/jquery-ui-highlight-multiple-dates-in-jquery-datepicker
the problem is that my datepicker is inline so i cant directly implement into the beforeShowDay: function(date) {
}
Pls post a demo on jsfiddle or something like that, it would be appreciated =D
*btw i tried to give beforeShowDay: ShowDay but this doesn't call the function
Alright i fixed it it was really easy XD, i had and old version of bootstrap datepicker. This version didnt support BeforeShowDay! I now got a newer version and it all works!
So I am using Yii and full calendar as a widget which is called in a view of CalendarController. Uppon call for a widget, the widget retrives existing events from the DB and puts them inside the full calendar to display. Now I have also made a simple filter for filtering out events by category they are in ( dropdown with a submit ), so I want to send request to a calendarController method called actionEvents() which then takes what is passed to it ( the category of events for which we want to retrieve events ), gets them back to the jQuery which then calls the calendar again passing it a json_encode(d) array of needed properties to correctly render events under the selected category in the dropdown. The problem I have is that it seems fullcalendar is doing my wanted call ( POST ) as well as one another GET call along with it for some reason so it does return properly formatted json to the jQuery from the method of controller, but just shows an empty calendar without events in it on return. This is how the console looks like after the returned data.
This is the code that calls ajax call
$(document).ready(function() {
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$('form.eventFilter').submit(function() {
var selectedOption = $('form.eventFilter select').val(),
eventContainer = $('.fc-event-container');
var objectToSend = { "categories" : [selectedOption],"datefrom" : "september2013"/*month + "" + year*/ , "dateto" : "september2013"/*month + "" + year*/};
$.ajax({
url: '<?php echo Yii::app()->createUrl('calendar/events'); ?>',
type: "POST",
async:false,
data: {data : JSON.stringify(objectToSend)},
success: function(data) {
$('#fc_calendar').html('');
$('#fc_calendar').fullCalendar({
events: data
});
console.log(data);
},
error: function() {
console.log(data);
}
});
return false;
})
})
The code that renders initial calendar events on first page load ( open ) is this
<div id="fc_calendar"></div>
<script class="fc_calendar_script">
// gets calendar and its events working and shown
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#fc_calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: [
<?php foreach ($eventItems as $event): ?>
{
title: '<?php echo htmlentities($event['eventItems']['title']); ?>',
start: new Date(y,m,d + <?php echo $event['eventItems']['startdate_day_difference']; ?>),
end: new Date(y,m,d + <?php echo $event['eventItems']['enddate_day_difference']; ?>),
url: '<?php echo $event['eventItems']['url']; ?>',
className: [
<?php foreach($event['eventCategories'] as $category) { echo ''.json_encode($category['slug']).','; }?> // and categories slugs as classnames, same purpose
]
},
<?php endforeach; ?>
]
});
</script>
The code in controller is not that important since you can see what it returns in the screenshot :) If someone has an idea of how to get around this I would really be grateful :) Tried everything I know
Ok so bounty goes to whoever answers this question :)
I am having problems with full calendar month rendering when ajax data is returned and events populated. Since I have checkboxes for each category ( events have MANY_MANY relation with categories ) and each time a checkbox is checked or unchecked, JSON array of chosen categories of events is passed on to PHP method which queries DB for all events that go under chose categories and returns all events in a jquery encoded array to the view which then takes that events array and rerenders the calendar like shown in the upper code.
Problem is that when a checkbox is checked or unchecked and ajax returned the calendar always renders on the current month ( so right now it would always rerender itself to show events for september, untill the end of the month, then always for Ocbober and so on ), but what if a user was on lets say November 2013 when he checked event category for which he wanted to filter the events? The calendar would rerender on September still. How could I make it rerender on the month the user was on when he checked / unchecked a checkbox ?
The code that I have which keeps track ( or at least it should ) of the current month when prev or next month buttons are clicked is this
$('.fc-button-next span').click(function(){
start = $('#fc_calendar').fullCalendar('getView').visEnd;
console.log(start);
});
$('.fc-button-prev span').click(function(){
start = $('#fc_calendar').fullCalendar('getView').visStart;
console.log(start);
});
However this code is not tracking properly, sometimes it skips a month, sometimes it stays on the month without change and sometimes it returns propper month, which is bugging me so I cant call this function of the calendar properly which should set calendar to propper month on rerender.
$('#fc_calendar').fullCalendar('gotoDate', start);
I think what you might be looking for is something like
jQuery(function($){
$('form.eventFilter').submit(function() {
$('#fc_calendar').fullCalendar( 'refetchEvents' );
return false;
});
$('#fc_calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: function(start, end, callback) {
var selectedOption = $('form.eventFilter select').val(),
eventContainer = $('.fc-event-container');
//create the data to be sent
var objectToSend = {
"categories": [selectedOption],
"datefrom": start.getDate() + '-' + start.getMonth() + '-' + start.getYear(),
"dateto": end.getDate() + '-' + end.getMonth() + '-' + end.getYear()
};
//use jsonp based jQuery request
$.ajax({
url: 'events.json',
data: objectToSend,
cache: false
}).done(function(data){
//on success call `callback` with the data
callback(data)
})
}
});
});
Demo: Plunker
Note: The date param formatting and jsonp is not used here, you will have to change it to match your requirements
I see that you use JSON.stringify(data); this is what i tought your error was
maybe you need a jsonp, and below you have my example
$.ajax({
'url': 'http://domain.com/index.php/api/news?callback=?',
'data': {'data': JSON.stringify(data), callback: 'jsonPCallback'},
'success': function(data) {
// console.log(data);
},
jsonpCallback: jsonPCallback,
dataType: 'jsonp'
});
function jsonPCallback(cbdata){
console.log('callback2')
// console.log(cbdata);
return false;
}
now, do you also use something like
echo $_GET['callback'].'('.CJSON::encode(array('status_live' => 1, 'data' => $data_decoded)).')';
in the controller to return the results ?
also, createUrl might be wrong, because you need a absolute path
Actualy the problem solution is as weird as the problem itself and it is the following. You must use designated way of doing an ajax call to fetch json that is in the plugin documentation, any other way you send your own call ( GET or POST ) and the calendar after that makes yet another call ( hence the another GET call ) if you are using just a "regular" $.ajax, $.post or $.get call using jQueries native functionality
This should really be posted somewhere on the website in some section so that people do not get confused why their calendar is not making ajax calls and I wonder how noone else had similar problem before . So this is the "correct" documentation way of calling it with full calendar which you can find HERE
$('#fc_calendar').html('');
$('#fc_calendar').fullCalendar({
eventSources: [
// your event source
{
url: '?r=calendar/events',
type: 'POST',
data: { data : JSON.stringify(objectToSend)},
error: function(data) {
alert(data);
},
}
// any other sources...
]
});
So it will automaticly fetch any returned ( properly formatted data ) and use it to rerender new calendar with those events. It is very weird way of doing it, but the only way that will work.
I can't comment so, you have an assignment to variable:"nothing" in your last query parameter
double check if you have looked for ajax request in your controller(important!),
and also if this is this a 404 by the apache, you have url rewriting problems,
and it looks like index.php is missing from url?!
I've created a code which disable certain dates retrieved from database.
Within getDates script I just retrieve dates from database, return them and assign them to array unavailableDates.
<script>
var unavailableDates;
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
$(document).ready(function()
{
$("#datepicker").datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: unavailable,
minDate: 0,
firstDay: 1, // rows starts on Monday
changeMonth: true,
changeYear: true,
showOtherMonths: true,
selectOtherMonths: true,
altField: '#date_due',
altFormat: 'yy-mm-dd'
});
$('#datepicker').focus(function(){
//alert($('#name').html());
$.ajax({
url: 'getDates.php',
data: "artist_id="+$('#name').html(),
dataType: 'json',
success: function(data)
{
unavailableDates = data;
}
});
})
});
</script>
It works fine but only when I click in datepicker twice. When I first click it shows all dates (no matter if they are available or not). When I click again, then it shows the unavailable dates.
Does anyone know why? Thanks
Add async: false into your ajax call so the app will wait for the response before continuing, like so
$('#datepicker').focus(function(){
//alert($('#name').html());
$.ajax({
url: 'getDates.php',
data: "artist_id="+$('#name').html(),
dataType: 'json',
async: false,
success: function(data)
{
unavailableDates = data;
}
});
Another thought, you could possibly add this ajax call right into the unavailable function rather then having two things that run first, onFocus and beforeShowDay (although I'm not terribly familiar with the beforeShowDay function)
This may slow down the opening of the date picker though, as it will have to wait for the service so it depends on how fast your service is and what performance requirements you have. Other options if this can be to slow would be to pop up a "getting dates" message or pull the server every X seconds while the page it up (although that could add a lot of extra service calls...)
EDIT: After this comment...
"basically when user selects an option (here they want to book artists so \
when user selects an artist), the unavailable dates of datepicker are
updated automatically."
it seems like loading the list when the artist is selected would make more sense, unless your concerned about changes while the page is open. In that case I would do something like...
On Artist Changed
-Disable date picker, possibly add a small note next to it / under it /
over it that it is loading
-Start ajax call with async true
-In ajax success function, re-enable the picker and remove the message.
This will allow the UI to stay active, allow the user to enter other information while the dates load, and if the service is fast enough, the won't even hardly know it was disabled for a second. Your dates won't be quite a "live" as the other way, but it doesn't sound like they need to be that live. You will need to recheck the dates when the form is submitted anyway.
Because you start the request for getting the unavailable dates when the datepicker is displayed. You have to do this in advance. In the callback of the backend request you can display the datepicker.
var data = $.getJSON($url, function (data) {
//your logic
}).success(function (data) {
//Trigger the first click
$('.datepicker').trigger('click');
});
$(".div_fader").on('click','.datepicker', function () {
$(this).datepicker();
});
I have downloaded jquery ui-date picker and implemented in my php web site. When I click on the date picker textbox it shows current date as selected. I need to display future date (current date+2) as select default
Is it possible?
See my code
$(function (){
// Datepicker
$('#requTravel').datepicker({
inline: true,
minDate: 0
});
//hover states on the static widgets
$('#dialog_link, ul#icons li').hover(
function() { $(this).addClass('ui-state-hover'); },
function() { $(this).removeClass('ui-state-hover'); }
);
});
Does anyone know this?
i have one more doubt. i have two calander. when i select a date from first calander say(1/07/2012) then my second calander will show 03/07/2012. ie date from the first calander +2 Is it possible?
Please reply
Thanks in advance
The minDate option accepts a few formats: http://jqueryui.com/demos/datepicker/#option-minDate
http://jsfiddle.net/n1ck/5GxcZ/5/
// Not Allowed to select before current date, default is 2 days from now
$('#requTravel').datepicker({
inline: true,
minDate: +2,
defaultDate: +2
});
// Allowed to select before current date, default is 2 days from now
$('#requTravel2').datepicker({
inline: true,
defaultDate: +2
});