jquery ui datepicker - beforeShowDay not working when I first open the clendar - jquery-ui

it looks like the beforeShowDay doesn't work the first time I open the calendar on the current month.
I'm having the jquery ui datepicker with few active days each month.
when I refresh the website and open the calendar for the first time, i'll see that all the dates in January are unactive but if I move to February and go back to Jan i'll see the active days (as I should the first time I opened it).
$("#divDatePicker").datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(value, date) {
//chose date
$("#search_term").val( $("#search_term").val() + value );
$("#divDatePicker").hide();
},
beforeShowDay: function(d) {
var year = d.getFullYear(),
month = ("0" + (d.getMonth() + 1)).slice(-2),
day = ("0" + (d.getDate())).slice(-2);
var formatted = year + '-' + month + '-' + day;
if ($.inArray(formatted, availableDates) != -1) {
return [true, "","Available"];
} else{
return [false,"","unAvailable"];
}
}
});
any ideas?

Consider the following example.
$(function() {
var availableDates = ["23-01-21", "23-01-22"];
$("#divDatePicker").datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(value, date) {
//chose date
var temp = $("#search_term").val();
temp += value;
$("#search_term").val(temp);
$("#divDatePicker").hide();
},
beforeShowDay: function(d) {
var formatted = $.datepicker.formatDate("y-mm-dd", d);
if (availableDates.indexOf(formatted) != -1) {
return [true, "", "Available"];
} else {
return [false, "", "unAvailable"];
}
}
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<div id="divDatePicker"></div>
<input type="text" id="search_term" />
You can use the utility $.datepicker.formatDate( format, date, options ) to format a Date into a String. You stated you wanted YY-MM-DD, so "23-01-05" for today. This must match with some of your availableDates elements, which I am assuming is an array.

Related

Add class to every nth element when i select date

How i can add class to every date under selected day.
Lets say i click on Thursday and all dates under Thursday have some class.
I have service where you can chose frequency, weekly, 2 weeks, 4 weeks, and when user click on some date add select frequency the dates are highlighted on the calendar.
I have try to add css to every nth child from ui-state-default but this is not working.
```
$('#cookdate').datepicker({
numberOfMonths: 2,
altField: '#selectedDatecook',
minDate: 2,
maxPicks: 20,
onSelect: function (date) {
var date = $(this).datepicker('getDate');
var day = date.getUTCDay();
},
});
You will want to use a combination of onSelect and beforeShowDate. For example:
$(function() {
var selected, final;
var days = 7;
$('#cookdate').datepicker({
numberOfMonths: 2,
minDate: 2,
onSelect: function(dStr, obj) {
selected = $.datepicker.parseDate("mm/dd/yy", dStr);
final = new Date(selected);
final.setDate(selected.getDate() + days);
$("#selectdate").val($.datepicker.formatDate("mm/dd/yy", final));
},
beforeShowDay: function(dt) {
$(".highlighted").removeClass("highlighted");
if (dt > selected && dt <= final) {
return [true, "highlighted"];
} else {
return [true, ""];
}
}
});
});
td.highlighted, td.highlighted a.ui-state-default {
background-color: #ccc;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Cook Date: <input type="text" id="cookdate"> Select Date: <input type="text" id="selectdate"></p>
You can change days to be any number of days you want. beforeShowDays will then look for the matching dates and add a class to them, highlighted.

Open date picker calendar using Glyphicon PRO calendar icon

I've got a week picker that is working great, but I'd like for the picker to open by clicking on the Glyphicons PRO icon for a calendar.
Anyone know how to use a Glyphicons PRO calendar icon instead of the input field to open the date picker's calendar?
I'd also like the calendar to correctly highlight rows as I hover over any date in that row. Now, the rows are highlighted only if my chosen date is within that week's range.
$(function () {
var startDate;
var endDate;
var selectCurrentWeek = function () {
window.setTimeout(function () {
$('.ui-weekpicker').find('.ui-datepicker-current-day a').addClass('ui-state-active').removeClass('ui-state-default');
}, 1);
}
var setDates = function (input) {
var $input = $(input);
var date = $input.datepicker('getDate');
if (date !== null) {
var firstDay = $input.datepicker("option", "firstDay");
var dayAdjustment = date.getDay() - firstDay;
if (dayAdjustment < 0) {
dayAdjustment += 7;
}
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment);
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment + 6);
var inst = $input.data('datepicker');
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('#startDate').text($.datepicker.formatDate(dateFormat, startDate, inst.settings));
$('#endDate').text($.datepicker.formatDate(dateFormat, endDate, inst.settings));
}
}
$('.week-picker').datepicker({
beforeShow: function () {
$('#ui-datepicker-div').addClass('ui-weekpicker');
selectCurrentWeek();
},
onClose: function () {
$('#ui-datepicker-div').removeClass('ui-weekpicker');
},
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function (dateText, inst) {
setDates(this);
selectCurrentWeek();
$(this).change();
},
beforeShowDay: function (date) {
var cssClass = '';
if (date >= startDate && date <= endDate) cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function (year, month, inst) {
selectCurrentWeek();
}
});
setDates('.week-picker');
var $calendarTR = $('.ui-weekpicker .ui-datepicker-calendar tr');
$calendarTR.live('mousemove', function () {
$(this).find('td a').addClass('ui-state-hover');
});
$calendarTR.live('mouseleave', function () {
$(this).find('td a').removeClass('ui-state-hover');
});
});
Here's my fiddle.... http://jsfiddle.net/notanothercliche/ke62p/
Instead of Glyphicons pro, jQuery UI datepicker is providing a calendar icons which can used lik
showOn: "button",
buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
buttonImageOnly: true
JSFiddle
As per your comments,
I have triggered the datepicker when the icon class is clicked,
$('.glyphicon-calendar').on('click', function () {
$('.week-picker').focus()
});
check this fiddle.
FYI .live is removed in jQuery 1.9.1 so replace .live with .on
You can use a label with "glyphicon" and "for" attribute
<label for="date_control" class="glyphicon glyphicon-calendar"></label>

How set end day based on start day in jQuery Mobile date picker?

I use jQuery-Mobile-DateBox for date and time picker in jQueryMobile.
<input id="start" type="date" data-role="datebox" data-options='{"mode": "calbox", "afterToday": true, "useFocus": true, "overrideDateFormat": "%m/%d/%Y"}'>
<input id="end" type="date" data-role="datebox" data-options='{"mode": "calbox", "afterToday": true, "useFocus": true, "overrideDateFormat": "%m/%d/%Y"}'>
I need not to allow user to select end day that are before start day.
$("#end").datebox("minDays", $("#start").val());
The above code doesn't work.
If you want to prevent end day from been lower then a start day
Working example: http://jsfiddle.net/Gajotres/QTuma/
HTML :
<label for="start-date">Start Date</label>
<input name="start-date" id="start-date" type="date" data-role="datebox" data-options='{"mode": "calbox", "useNewStyle":true,"overrideDateFormat":"%-m/%-d/%Y"}'/>
<label for="end-date">End Date</label>
<input name="end-date" id="end-date" type="date" data-role="datebox" data-options='{"mode": "calbox", "useNewStyle":true,"overrideDateFormat":"%m/%-d/%Y"}'/>
Javascript
$('#end-date').bind('datebox', function(e, p) {
if ( p.method === 'set' && $('#start-date').val().length > 0) {
e.stopImmediatePropagation();
var startDate = new Date($('#start-date').val());
var endDate = new Date($('#end-date').val());
if (startDate > endDate)
{
$('#end-date').val('');
}
}
});
Here is how to disabled date as per selection of start or end dates:
If a date is selected in start datebox, then end date will be limited to selection of days after start date (inclusive of start date) and vise-verse for end date too.
$(document).on('pageinit', '#index', function(){
$('#end-date').bind('datebox', function(e, p) {
if ( p.method === 'open') {
// Make it a date
var startDate = new Date($('#start-date').val());
var todaysDate = new Date();
// Length of 1 Day
var lengthOfDay = 24 * 60 * 60 * 1000;
// Get the difference
var diff = parseInt((((startDate.getTime() - todaysDate.getTime()) / lengthOfDay)+1)*-1,10);
// Set minDays to disallow anything earlier
$('#end-date').datebox({'minDays': diff});
}
});
$('#start-date').bind('datebox', function(e, p) {
if ( p.method === 'open') {
// Make it a date
var endDate = new Date($('#end-date').val());
var todaysDate = new Date();
// Length of 1 Day
var lengthOfDay = 1000 * 60 * 60 * 24;
// Get the difference
var diff = parseInt((((endDate.getTime() - todaysDate.getTime()) / lengthOfDay)+1),10);
// Set minDays to disallow anything earlier
$('#start-date').datebox({'maxDays': diff});
}
});
});
check the updated fiddle link: http://jsfiddle.net/QTuma/6/
OR as per below solution a simpler method to set min and max:
$(document).on('pageinit', '#index', function(){
$('#start-date').bind('datebox', function(e, p) {
if ( p.method === 'set') {
var endDate = $('#start-date').val().replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})$/,'$3-$1-$2');
$('#end-date').attr({'min':endDate,'max':'2999-01-01'});
$('#end-date').datebox('applyMinMax');
}
});
$('#end-date').bind('datebox', function(e, p) {
if ( p.method === 'set') {
var endDate = $('#end-date').val().replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})$/,'$3-$1-$2');
$('#start-date').attr({'min':'1000-01-01','max':endDate});
$('#start-date').datebox('applyMinMax');
}
});
});

How to restrict jqueryui date range?

I have two date-pickers #from and #to, as usual, now what I need to do is make sure that the date range selected between the two is always within 3months of each other. So basically, on selecting one of the pickers, I need to set minDate/maxDate option for the other one relative to the selected date, But I don't know what would be the best way to find these relative dates. Any suggestions?
Alternatively you could do it like this:fiddle
Both ways are valid, i suppose.
.js
$("#startDatePicker").datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(dateText,dateObj){
var dateObject = $(this).datepicker("getDate");
dateObject.setMonth(dateObj.currentMonth+3);
$("#endDatePicker").datepicker( "option", "maxDate",dateObject);
}
});
$("#endDatePicker").datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
onSelect: function(dateText,dateObj){
var dateObject = $(this).datepicker("getDate");
dateObject.setMonth(dateObj.currentMonth-3);
$("#startDatePicker").datepicker( "option", "minDate",dateObject);
}
});
I have created a jsfiddle.The range between the days is set to 3 days.you can edit based on ur requirement
$(document).ready(function () {
$("#startDatePicker").datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function (date) {
if ($('#endDatePicker').val() == "") {
var selectedDate = new Date(date);
var secsPerDay = 86400000;
var endDate = new Date(selectedDate.getTime() + 2 * secsPerDay);
alert(endDate);
$("#endDatePicker").datepicker("option", "minDate", selectedDate);
$("#endDatePicker").datepicker("option", "maxDate", endDate);
}
}
});
$("#endDatePicker").datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
onSelect: function (date) {
if ($('#startDatePicker').val() == "") {
var selectedDate = new Date(date);
var secsPerDay = 86400000;
var startDate = new Date(selectedDate.getTime() - 5 * secsPerDay);
$("#startDatePicker").datepicker("option", "minDate", startDate);
$("#startDatePicker").datepicker("option", "maxDate", selectedDate);
}
}
});
});
and HTML
<p>Start Date:
<input type="text" id="startDatePicker"/>
</p>
<p>End Date:
<input type="text" id="endDatePicker"/>
</p>

jQuery UI DatePicker output date format

I have inline jQuery UI DatePicker and need to customize format and look of output date, code:
<div id="date-start"></div>
<div class="date start" id="date-start-output"></div>
$(function(){
// Datepicker
$('#date-start').datepicker({
inline:true,
showOtherMonths: true,
altField: "#date-start-value",
altFormat: "dd M yy",
dateFormat: "dd M yy",
onSelect: function(){
var day1 = $("#date-start").datepicker('getDate').getDate();
var month1 = $("#date-start").datepicker('getDate').getMonth() + 1;
var year1 = $("#date-start").datepicker('getDate').getFullYear();
var str_output = "<b>" + day1 + "</b><span>" + month1 + "<br />" + year1 + "</span>";
$('#date-start-output').html(str_output);
}
});
});
It works, but in #date-start-output I have date format not as "dd M yy" but as "dd m yy". How can set necessary output format for month?
Also I need to show in #date-start-output current date after page load, I'm trying "beforeShow" event, but it not work together with "onSelect" event for me.
Thanks.
onSelect event handler first parameter is the selected date as text.
I guess it would be formatted as specified during the initialization
See http://jqueryui.com/demos/datepicker/#event-onSelect
$(function(){
// Datepicker
$('#date-start').datepicker({
inline:true,
showOtherMonths: true,
altField: "#date-start-value",
altFormat: "dd M yy",
dateFormat: "dd M yy",
onSelect: function(dateText){
$('#date-start-output').html(dateText);
}
});
});
If you need special formatting, you can try:
$(function(){
// Datepicker
$('#date-start').datepicker({
...
onSelect: function(){
var dateText = $.datepicker.formatDate("<b>dd</b><span>M<br />yy</span>", $(this).datepicker("getDate"));
$('#date-start-output').html(dateText);
}
});
});
Not sure it will work with HTML tags though

Resources