I have been trying to find a clear explanation for a significant amount of time now but I just can't seem to understand how this method works. Below is the official documentation from the Jquery UI API. It may be clear to others but I find it a bit vague. I simply want to take an array of dates and disable them. I am able to make all dates not selectable but not the ones I want.
beforeShowDayType: Function( Date date )
Default: null
A function that takes a date as a parameter and must return an array with:
[0]: true/false indicating whether or not this date is selectable
[1]: a CSS class name to add to the date's cell or "" for the default presentation
[2]: an optional popup tooltip for this date
The function is called for each day in the datepicker before it is displayed.
This is my (incomplete) code so far.
$(document).ready(function() {
var array = ["2014-01-03","2014-01-13","2014-01-23"];
$('#fromDate').datepicker({
dateFormat: "yy-mm-dd",
beforeShowDay: function(date) {
{
return [false, "", "Booked out"];
} else {
return [true, "", "available"];
}
}
});
});
Try this:
beforeShowDay: function(date) {
if($.inArray($.datepicker.formatDate('yy-mm-dd', date ), array) > -1)
{
return [false,"","Booked out"];
}
else
{
return [true,'',"available"];
}
}
Related
Here is the code where the user enters a date: (it has to be a date picker on my end, but the form has to submit the date field as text – don’t ask)
On submit, I call validation logic in javascript. I’ve attached a screenshot of what it looks like when I try to enter 01/01/2001 as the users birthday. It looks like when I’m converting the value string to a Date object, it’s converting to the wrong date and time. If it would just convert correctly, I could adjust the month and day and year and build a string to send in my second object.
Attaching the picture…
I’ve messed around with UTC and timezones, but to no avail.
I need my output to be a text string "01/01/2001" which I can build as long as I have the correct date going in..but it seems to calculate wrong no matter what I try.
When you construct the Date it is assumed that the string represents a time in UTC since no timezone was provided. The string is parsed as UTC, but the Date object uses your browser's local timezone.
One way to fix that is to use getUTCDay instead of getDay. Same applies to month and year.
Using a jquery datapicker library did the trick.
function initDatePickers() {
jQuery('.om-datepicker-trigger').click(function () {
var defaultDatePickerOptions = {
showOtherMonths: true,
changeMonth: true,
changeYear: true,
defaultDate: '-45y',
dateFormat: 'mm/dd/yy',
beforeShow: function (input, inst) {
var widget = jQuery(inst).datepicker('widget');
widget.css('margin-left', jQuery(input).outerWidth() + 3 -
widget.outerWidth());
},
//buttonImage: "/img/button_calendar.png",
//buttonImageOnly: true,
showOn: "both"
};
var $input = jQuery(this).parent().find('.om-input-date').first();
if ($input.hasClass('om-min-date-today')) {
var minDateTodayOptions = defaultDatePickerOptions;
minDateTodayOptions.defaultDate = 0;
minDateTodayOptions.minDate = 0;
$input.datepicker(minDateTodayOptions);
$input.datepicker('show');
} else {
$input.datepicker(defaultDatePickerOptions);
$input.datepicker('show');
}
});
jQuery('.om-input-date').click(function () {
jQuery(this).next('.om-datepicker-trigger').trigger('click');
});
// Datepicker
// --------------------------------------------------------
jQuery('.om-input-date').keyup(function () {
var inputDOBBox = jQuery(this);
var dateValue = inputDOBBox.attr('value');
if (dateValue.length == 3 || dateValue.length == 6) {
var first = dateValue.substring(0, dateValue.length - 1);
var last = dateValue.substring(dateValue.length - 1);
if (last != "/" && last != "-") {
inputDOBBox.attr('value', first + "/" + last);
}
}
});
Is there any function to get the input that was provided to moment()
In the example below, inputDate becomes null.
var date = moment("invalid date");
if(!data.isValid()){
return { message: "Invalid date", inputDate: date }
}
I can access the input using internals i.e. date._i but was wondering if there's any function that would return the input provided to moment constructor.
You can use creationData()
After a moment object is created, all of the inputs can be accessed with creationData() method:
moment("2013-01-02", "YYYY-MM-DD", true).creationData() === {
input: "2013-01-02",
format: "YYYY-MM-DD",
locale: Locale obj,
isUTC: false,
strict: true
}
Here a live example:
var date = moment("invalid date", moment.ISO_8601);
console.log(date.creationData().input);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
As a side note:
I've used moment.ISO_8601 in my snippet to prevent Deprecation Warning, as shown here.
Something quite similar was asked (but not a duplicate) was asked here.
Main question: How to set closest available date?
Hi all, i'm using bootstrap-datetimepicker.
I've disabled some days from calendar and sometimes current date in range.
So it disables successfully but I want to preset default date into the input value, if I use defaultDate: 'moment' it sets current date (which is disabled).
How to set closest available date?
Does exist any lifehack to resolve it?
Or should I make it manually?
This is how it works now:
var $datesDisabled = [];
$.each($dates, function (key, value) {
$datesDisabled.push(moment(value))
});
// PARAMS TO DATETIMEPICKER
var $params = {
locale: 'en',
format: 'DD/MM/YYYY',
disabledDates: $datesDisabled,
};
// CHECK IF CURRENT DATE IS IN DISABLED ARRAY
if ($.inArray(moment().format('MM/DD/YYYY'), $dates) === -1) {
// IF NOT PRESET CURRENT DATE
$params.defaultDate = 'moment';
} else {
// DO NOT PRESET
$params.useCurrent = false;
}
$('.datetimepicker').datetimepicker($params);
According to the library documentation, you're not supposed to use defaultDate: 'moment'. They do mention the following:
Accepts: date, moment, string
But it means you can provide a Date object, a moment() object or a date string. The string "moment" is none of those, so it probably defaults to today.
However, you can configure the defaultDate like this:
// Using a date string
$('#my-date-picker').datetimepicker({
defaultDate: '2016-08-20'
});
// Using a Date object
$('#my-date-picker').datetimepicker({
defaultDate: new Date('2016-08-20')
});
// Using a moment.js object
$('#my-date-picker').datetimepicker({
defaultDate: moment('2016-08-20')
});
But if you want to have the defaultDate the closest date according to your disabled dates, you'll have to calculate it by yourself. For such a functionality you could create a recursive function that recalls itself with the given date minus or plus 1 until it finds one that is not disabled.
For example:
var disabled = [
new Date('2016-01-03'),
new Date('2016-01-04'),
new Date('2016-01-05'),
new Date('2016-01-08')
];
function getClosest(date, disabled, direction) {
if(!containsDate(disabled, date)) {
return date;
} else {
var prev = getClosest(date.clone().add(direction || -1, 'days'), disabled, direction || -1),
next = getClosest(date.clone().add(direction || 1, 'days'), disabled, direction || 1);
if (Math.abs(date.diff(prev, 'days')) > Math.abs(date.diff(next, 'days'))) {
return next;
} else {
return prev;
}
}
}
function containsDate(dates, given) {
return dates.some(function(date) {
return given.isSame(date, 'day');
});
}
console.log(getClosest(moment('2016-01-02'), disabled).toDate());
console.log(getClosest(moment('2016-01-03'), disabled).toDate());
console.log(getClosest(moment('2016-01-04'), disabled).toDate());
console.log(getClosest(moment('2016-01-05'), disabled).toDate());
console.log(getClosest(moment('2016-01-06'), disabled).toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
Im trying to get the weeknumber and the name/shortcut of the weekday according to the chosen date through a JQuery calendar.
Im not really proficient in JQuery so i can get the weeknumber, but i cant seem to get the name of the day with it.
Could anyone help me out?
$('#datepicker').datepicker({
onSelect: function (dateText, inst) {
$('#weekNumber').val($.datepicker.iso8601Week(new Date(dateText)));
}
});
you have to get the date, than extract the name of the day from it:
var date = $(this).datepicker('getDate');
alert($.datepicker.formatDate('DD', date));
hope it helps!
edit: you can find the working fiddle here.
You can add in your existing block to grab the day name, by using the format date syntax, found in the datepicker documentation, here:
http://api.jqueryui.com/datepicker/#utility-formatDate
In this case, full day name is obtained from 'DD', so your updated code might look like:
$('#datepicker').datepicker({
onSelect: function (dateText, inst) {
var d = new Date(dateText);
$('#weekNumber').val($.datepicker.iso8601Week(d));
$('#dayName').val($.datepicker.formatDate('DD', d));
}
});
Fiddle here: http://jsfiddle.net/duffmaster33/zL6m2wck/
Here is alot of information on how to use the javascript Date object.
Here is the code I suggest you:
$(function() {
$( "#datepicker" ).datepicker({
onSelect: function( dateText, dateObj ){
//You can get your date string that way
console.log(dateText);
//You can get a few value about the date, look in your console to see what you can do with that object
//i.e. - console.log(dateObj.selectedDay)
console.log(dateObj);
//You can see the result of the date in string that way
$('.string').append(dateText);
currDate = new Date(dateText);
//You can have a complete Date object using the Date javascript method
console.log(currDate);
//The Date object in javascript provides you all you need then
//Get the number of day in a week, from 0(Sunday) to 6(Saturday)
$('.getday').append(currDate.getDay());
//Create a function to see day Sun - Sat
function getWeekDay(date) {
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
return days[ date.getDay() ]
}
//Then we use it
$('.getweekday').append(getWeekDay(currDate));
}
});
});
You can see my fiddle there:
https://jsfiddle.net/qapw32Lp/
Here is a great source of information you can use also abotu the Date Object:
http://javascript.info/tutorial/datetime-functions
Forgive me as I'm a bit novice to JS, just know enough to manipulate.
For those familiar with Isotope ( http://isotope.metafizzy.co/docs/sorting.html ), I have a button at the top of a page to sort by date. Isotope finds the element
<span class="date"> 01/04/2012 </span>
with this:
$container.isotope({
getSortData : {
date : function ( $elem ) {
return $elem.find('.date').text();
}});
Which works fine, but I need to flip (descend) the date order
Isotope has a function:
$('#container').isotope({
sortBy : 'date',
sortAscending : false
});
But I can't get it to work - that just makes the default set sort by date, rather than sorting when I click. I think this is just a question of syntax... how/where can I put sortAscending: false ??
Thanks...
EDIT Viewing some source from Demos, I see that:
<a href="#sortAscending=false">
Can be done, but I'm already sorting by passing this:
<a href="#sortBy=date">
Which finds a the span from earlier with the date info...
Here is how I did it, jsFiddle
$container.isotope({
itemSelector: '.element',
getSortData: {
date: function ($elem) {
return Date.parse($elem.find('.date').text());
}
}
});
It doesn't seem to matter what format the date is in, and works ascending and descending.
The parse() method parses a date string and returns the number of milliseconds between the date string and midnight of January 1, 1970.
Basically it turns your date strings into nice solid numbers which are easy to compare.
Heres what I did to sort by date.
If your date is in the format of '01/01/2012' then you need to convert it to a javascript date object.
getSortData: {
date: function ($elem) {
var dateStr = $elem.find('.date').text(),
dateArray = dateStr.split('/'),
year = dateArray[2],
month = dateArray[0],
day = dateArray[1];
return new Date(year, month, day);
}
}
then you do your usual
$('#container').isotope({ sortBy: 'date' });