javascript calendar - highlight specific days - javascript

I have a datepicker javascript calendar that highlights specific holidays with a specific color.
I need it to highlight the days Wednsday (3) - Saturday (6) as well and am struggling.
Here is the code I am using thus far:
<script type="text/javascript">
$(document).ready(function() {
var SelectedDates = {};
SelectedDates[new Date('01/01/2014')] = new Date('01/01/2014');
SelectedDates[new Date('01/02/2014')] = new Date('01/02/2014');
SelectedDates[new Date('01/03/2014')] = new Date('01/03/2014');
$('#date1, #date2').datepicker({
beforeShowDay: function(date) {
var Highlight = SelectedDates[date];
if (Highlight) {
return [true, "highlighted", Highlight];
}
else {
return [true, '', ''];
}
}
});
});
</script>
The CSS looks like this:
.highlighted a{background:#f57d31 !important;}
And the form looks like this:
<input id="date1" name="date1" size="12" type="text" />
Please help on the best route to highlight Wednsday (3) - Saturday (6) on entire calendar.
Thanks~!

The following highlights Wednesday through Saturday for the months May through September:
$('#date1, #date2').datepicker({
beforeShowDay: function (date) {
var day = date.getDay();
var month = date.getMonth();
return [(day>=3 && day<=6)&&(month>=4 && month<=8), "highlighted"];
}
});
jsFiddle example

Related

MD Datepicker shows the full date after selecting Month and year from month and year calendar mode

I am using Material Design and had to display the month and year only. So I used the month mode. But now when a user select a year and month, the whole date is visible for example if i had selected February 2019 from the datepicker, it would display that you selected 01/02/2019. Instead we want just Feb-2019.
This is my html md code
<md-input-container flex="100" layout="column">
<div style="font-size: 10px; color: blue;"
label ng-bind="::dateFields[2].label">
</div>
<md-datepicker ng-model="dateFields.selectedDate"
ng-required="dateFields.required"
md-date-locale="dateFields.locale"
md-mode="month"
md-open-on-focus="true">
</md-datepicker>
What shall i edit in order to just get the month and year after selection?
you can make use of moment js for formatting date as you wanted,
var monthFormat = buildLocaleProvider("MMM-YYYY");
var ymdFormat = buildLocaleProvider("YYYY-MM-DD");
function buildLocaleProvider(formatString) {
return {
formatDate: function(date) {
if (date) return moment(date).format(formatString);
else return null;
},
parseDate: function(dateString) {
if (dateString) {
var m = moment(dateString, formatString, true);
return m.isValid() ? m.toDate() : new Date(NaN);
} else return null;
}
};
}
$scope.dateFields = {
......
locale: monthFormat
};
Look into this demo https://plnkr.co/edit/eV2Kmt.
Reference answer - Angular-Material set a Datepicker with only months and years

Highlighting multiple dates on jquery ui datepicker calendar works fine when clicking directly, but not when triggered by external button

I'm using the following to create a calendar that I can select multiple days for. It stores which days are turned "on" by using an object with values set to 1/0 true/false based on which days are selected.
Then I have a function that adds a "selected" class to each day that is turned on. It works flawlessly when I'm clicking dates manually, but I created buttons to select specific days (or date ranges later if I can get this working), but for some reason the code that highlights the days only works when clicking directly and not when using the buttons.
What the actual freck is going on?
<div id="days_cal_area">
<div id="days_cal"></div>
<div id="last_day" >Last</div>
</div>
<script>
// Maintain array of dates
var days = {};
$('#days_cal').datepicker({
inline: true,
firstDay: 0,
showOtherMonths: false,
selectOtherMonths: false,
dateFormat: 'yy-mm-dd',
changeYear: false,
defaultDate: new Date(1995, 0, 1),
onSelect: function (dateText, inst) {
day = parseInt(dateText.split('-')[2])
days[day] = !days[day];
daysStr();
},
beforeShowDay: function (date) {
var day = date.getDate();
if (days[day])
return [true, " date_selected day_"+day];
return [true, "day_"+day];
}
});
</script>
<div class="button_area row_items days_buttons">
<div class="sm_button" select="1" type="day">The 1st</div>
<div class="sm_button" select="15" type="day">The 15th</div>
<div class="sm_button" id='last_button'>Last day</div>
</div>
<div class="hidden_field">
<?php $task_form->write_fields(['days','weekdays','weeks','months']); ?>
</div>
<script>
function daysStr(){
console.log(days);
// Clear selected days
$('#days_cal .date_selected').removeClass('date_selected');
// Build a string for the form
temp = [];
$.each(days,function(day,addIt){
if (addIt) {
// Add it to the string for form submission
temp.push(day);
// Also mark it on the calendar
$('[data-day='+day+']').addClass('date_selected');
}
})
// Now add it to the form
$('#days_area [name=days]').val(temp.join(','));
}
$(document).ready(function(){
// prep the calendar (ONE TIMEM THINGS)
$('#days_area a').each(function(){
theTD = $(this).closest('td');
day = $(this).text();
$(theTD).data('day',day);
})
$('#days_area [type=day]').click(function(){
tempDays = $(this).attr('select').split(','); // Comma list of days
$(tempDays).each(function(index,day){
days[day] = true;
})
daysStr();
})
$('#last_button').click(function(){
$(this).toggleClass('on');
if ($(this).hasClass('on')){
$('#last_day').show();
days['last'] = true;
}
else {
$('#last_day').hide();
days['last'] = false;
}
daysStr();
})
})
</script>

Datepicker set default date

I am trying to set default date for Jquery datepicker on init. Here is my html:
var content = "";
content = "<table class=\"filter-table\">";
content += "<tr><td><label for='startDate'>From </label></td><td><input name='startDate' id='startDate' class='date-picker' /></td></tr>";
content += "<tr><td> </td></tr>";
content += "<tr><td><label for='endDate'>To </label></td><td><input name='endDate' id='endDate' class='date-picker' /></td></tr>";
And my JavaScript:
<script type="text/javascript">
function showdatepicker() {
$('.date-picker').datepicker( {
changeMonth: true,
changeYear: true,
changeDay: true,
showButtonPanel: true,
dateFormat: 'yy-mm-dd',
onClose: function(dateText, inst) {
var day = $("#ui-datepicker-div .ui-datepicker-day :selected").val();
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$('#startDate').datepicker({defaultDate: -30});
$('#endDate').datepicker({defaultDate: new Date()});
}
});
}
</script>
What I am trying to do is set the date and show in the textbox when on load the page. The endDate should be current date whilst start date should be one month before. However, by using these codes, it does not display the date in textbox when first load.
I wonder why is it so. Thanks in advance.
I, like you, could not use a method on the datepicker to populate a default date in the input.
So instead, I made code using vanilla JS to calculate the default dates and format them to display in the textboxes.
Here is the JS I added:
function showdatepicker() {
// same as yours
}
function populateDefaultValues() {
var today = new Date();
var month = today.getMonth() - 1,
year = today.getFullYear();
if (month < 0) {
month = 11;
year -= 1;
}
var oneMonthAgo = new Date(year, month, today.getDate());
$('#startDate').val($.datepicker.formatDate('yy-mm-dd', today));
$('#endDate').val($.datepicker.formatDate('yy-mm-dd', oneMonthAgo));
}
$(function() {
populateDefaultValues();
showdatepicker();
});
jsFiddle
Have a look at the defaultDate option. It provides exactly the features you need.
Because the default date options will vary for each datepicker you will need to initialise them separately (basically copy-paste, and tweak to suit).
http://api.jqueryui.com/datepicker/#option-defaultDate

jQuery add 7 days to date (input and output type text)

I am trying to do a simple page that takes a date (input type TEXT), and once the date is entered, another field will add 7 days to the input and display the date (+7 days) in a text input. My knowledge of jQuery is limited so I may have a small bug...
<html>
<head>
<title>Date Plus 7 Days</title>
<script type="text/javascript">
$(document).ready(function(){
function DateFromString(str){
str = str.split(/\D+/);
str = new Date(str[2],str[0]-1,(parseInt(str[1])+7));
return MMDDYYYY(str);
}
function MMDDYYYY(str) {
var ndateArr = str.toString().split(' ');
var Months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec';
return (parseInt(Months.indexOf(ndateArr[1])/4)+1)+'/'+ndateArr[2]+'/'+ndateArr[3];
}
function Add7Days() {
var date = $('#start_date').val();
var ndate = DateFromString(date);
return ndate;
}
$('#start_date').change(function(){
$('#end_date') = Add7Days();
})
});
</script>
</head>
<body>
Start Date
<input type="text" id="start_date" value=''>
<br>
End date
<input type="text" id="end_date" value=''>
</body>
</html>
What did I do wrong?
Thanks!
you've attempted to assign an object to $('#end_date'). jQuery deals with this in a different way by altering the value of the input box by leveraging .val('value-here')
Try this:
$('#start_date').change(function(){
$('#end_date').val(Add7Days());
});
See this fiddle: http://jsfiddle.net/zydZ2/
Also, Moment.JS is great for parsing and manipulating dates, I'd strongly recommend checking that out: http://momentjs.com/
Hope this helps!
functionally to add 7days to an existing date can be achieved by using
var today_date = new Date()
alert(today_date)
today_date.setDate(today_date.getDate() + 7)
alert(today_date)
this will add seven days to an existing date if its 31 than it will make it 7th of next month
hope this help
Your may using JQuery & JqueryUI datepicker featured to did it.
$('#start_date').datepicker({
dateFormat: 'mm/dd/yy',
minDate: 0,
});
$("#end_date").datepicker({
dateFormat: 'mm/dd/yy',
minDate: 7,
});
var _dt = new Date();
var _dt = _dt.setDate(_dt.getDate());
$("#start_date").datepicker("setDate","mm/dd/yy", _dt);
$("#end_date").datepicker("setDate", "mm/dd/yy", _dt);
you may refer this http://jsfiddle.net/o9grLdf0/12/
min = 0 for input startdate = today date
and
min = 7 mean today + 7 day for enddate
function listDatesBetweenTwoDates(S_dateA, S_dateB) {
var O_dateA = moment(S_dateA).add(1, 'd');
var O_dateB = moment(S_dateB).add(1, 'd');
var O_itr = moment.twix(O_dateA, O_dateB).iterate("days");
var A_range = [];
while (O_itr.hasNext()) {
A_range.push(O_itr.next().toDate())
}
return A_range;
}

How to restrict the selectable date ranges in Bootstrap Datepicker?

I need to use datepicker which provides me the option of restricting the selectable dates. We had been using jQuery UI which is used to support it using minDate, maxDate options.
$("#id_date").datepicker({minDate: +1, maxDate: '+1M +10D'});
Recently we started using Twitter Bootstrap for our styles. And apparently, Twitter Bootstrap is incompatible with jQuery UI styles. So I tried using one of the bootstrap compatible datepickers available at http://www.eyecon.ro/bootstrap-datepicker/.
Unfortunately, the above plugin is not as configurable as jQuery UI's datepicker. Can anyone help me out with restricting the selectable date ranges in the new datepicker.
The Bootstrap datepicker is able to set date-range. But it is not available in the initial release/Master Branch. Check the branch as 'range' there (or just see at https://github.com/eternicode/bootstrap-datepicker), you can do it simply with startDate and endDate.
Example:
$('#datepicker').datepicker({
startDate: '-2m',
endDate: '+2d'
});
With selectable date ranges you might want to use something like this. My solution prevents selecting #from_date bigger than #to_date and changes #to_date startDate every time when user selects new date in #from_date box:
http://bootply.com/74352
JS file:
var startDate = new Date('01/01/2012');
var FromEndDate = new Date();
var ToEndDate = new Date();
ToEndDate.setDate(ToEndDate.getDate()+365);
$('.from_date').datepicker({
weekStart: 1,
startDate: '01/01/2012',
endDate: FromEndDate,
autoclose: true
})
.on('changeDate', function(selected){
startDate = new Date(selected.date.valueOf());
startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
$('.to_date').datepicker('setStartDate', startDate);
});
$('.to_date')
.datepicker({
weekStart: 1,
startDate: startDate,
endDate: ToEndDate,
autoclose: true
})
.on('changeDate', function(selected){
FromEndDate = new Date(selected.date.valueOf());
FromEndDate.setDate(FromEndDate.getDate(new Date(selected.date.valueOf())));
$('.from_date').datepicker('setEndDate', FromEndDate);
});
HTML:
<input class="from_date" placeholder="Select start date" contenteditable="false" type="text">
<input class="to_date" placeholder="Select end date" contenteditable="false" type="text"
And do not forget to include bootstrap datepicker.js and .css files aswell.
The example above can be simplify a bit. Additionally you can put date manually from keyboard instead of selecting it via datepicker only. When clearing the value you need to handle also 'on clearDate' action to remove startDate/endDate boundary:
JS file:
$(".from_date").datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
}).on('changeDate', function (selected) {
var startDate = new Date(selected.date.valueOf());
$('.to_date').datepicker('setStartDate', startDate);
}).on('clearDate', function (selected) {
$('.to_date').datepicker('setStartDate', null);
});
$(".to_date").datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
}).on('changeDate', function (selected) {
var endDate = new Date(selected.date.valueOf());
$('.from_date').datepicker('setEndDate', endDate);
}).on('clearDate', function (selected) {
$('.from_date').datepicker('setEndDate', null);
});
HTML:
<input class="from_date" placeholder="Select start date" type="text" name="from_date">
<input class="to_date" placeholder="Select end date" type="text" name="to_date">
Most answers and explanations are not to explain what is a valid string of endDate or startDate.
Danny gave us two useful example.
$('#datepicker').datepicker({
startDate: '-2m',
endDate: '+2d'
});
But why?let's take a look at the source code at bootstrap-datetimepicker.js.
There are some code begin line 1343 tell us how does it work.
if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
var part_re = /([-+]\d+)([dmwy])/,
parts = date.match(/([-+]\d+)([dmwy])/g),
part, dir;
date = new Date();
for (var i = 0; i < parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]) {
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
}
There are four kinds of expressions.
w means week
m means month
y means year
d means day
Look at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$.
You can do more than these -0d or +1m.
Try harder like startDate:'+1y,-2m,+0d,-1w'.And the separator , could be one of [\f\n\r\t\v,]
Another possibility is to use the options with data attributes, like this(minimum date 1 week before):
<input class='datepicker' data-date-start-date="-1w">
More info: http://bootstrap-datepicker.readthedocs.io/en/latest/options.html
i am using v3.1.3 and i had to use data('DateTimePicker') like this
var fromE = $( "#" + fromInput );
var toE = $( "#" + toInput );
$('.form-datepicker').datetimepicker(dtOpts);
$('.form-datepicker').on('change', function(e){
var isTo = $(this).attr('name') === 'to';
$( "#" + ( isTo ? fromInput : toInput ) )
.data('DateTimePicker')[ isTo ? 'setMaxDate' : 'setMinDate' ](moment($(this).val(), 'DD/MM/YYYY'))
});
<script type="text/javascript">
$(document).ready( function() {
$("#submitdate").datepicker( {
minDate: 0,
maxDate: 0,
dateFormat: "yy-mm-dd",
});

Categories

Resources