Today link with datepicker like the one in django admin page - javascript

I am looking to create a datetime calender same as in django admin page using jQuery. I am using datepicker() api for this and it works cool
jQuery ui datepicker
Below is what I can do with this :
but I am still looking to have a today link like it is provided in django admin page, as shown in figure below in red:
Is it possible to do using same datepicker ? Or maybe we would need to do something else ?
Any suggestions ?
Code which I am using in current datepicker is below :
<script>
$(function() {
$("[name*='exp_date']").datepicker({ changeMonth: true , changeYear: true,
dateFormat: "yy-mm-dd" ,gotoCurrent: true,appendText: "(yyyy-mm-dd)" ,
autoSize: true , prevText: "Earlier" ,showButtonPanel: true , showCurrentAtPos: 3, showOptions: { direction: "up" }, weekHeader: "Wk" });
});
</script>
<style>
.ui-datepicker-trigger { position:relative;top:5px; height:20px ; }

You can always customize it with a bit of javascript and make it work as you want. Check this fiddle
$("#todaylink").on("click", function(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'/'+dd+'/'+yyyy;
$("#today").val(today);
});
Javascript based on this question.

You could just use jQuery to populate the input box with todays date.
Here's a fiddle for an example: http://jsfiddle.net/9XtfX/
JS
function setDate() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
$('#todaysDate').val(today);
}
$('#setDate').click(function(){
setDate();
});
HTML
<form action="#" method="post" class="" id="form">
<input type="text" id="todaysDate" name="todaysDate" value="" />
<input type="button" id="setDate" value="Today"></input>
</form>

Related

How to Set 2 different date in materialize datepicker using Javascript?

i am using Materialize template, I am trying to create 2 different default Date which is today and 2 days ago with javascript like this:
However, materialize only allow one default date using defaultDate using:
var elems = document.querySelectorAll('.datepicker');
var instances = M.Datepicker.init(elems, {defaultDate: new Date(),
setDefaultDate: true });
which set both dates to only one default date to
is there a way to set 2 different Default dates?
I found the way to do it, it's assigning them manually using their Input ID
// check current date
var d = new Date();
// recreate new date as mm/dd/yyyy to new date then subtract 2 in day
var dayBefore = new Date( (d.getMonth()+ 1) +"/" + (d.getDate()-2) + "/" + d.getFullYear());
// load datepicker class style from materialize
// and set default date for the cards
// getmonth() + 1 because the month start in 0 not 1
var elems = document.getElementById('FirstElement');
var instances = M.Datepicker.init(elems, {format: 'dd/mm/yyyy', defaultDate: dayBefore ,
setDefaultDate: true });
var elems = document.getElementById('SecondElement');
var instances = M.Datepicker.init(elems, {format: 'dd/mm/yyyy', defaultDate: d,
setDefaultDate: true });
And here's the HTML:
<input id="FirstElement" type="text" class="datepicker">
<label for="start_date">Start Date</label>
<input id="SecondElement" type="text" class="datepicker">
<label for="end_time">End Time</label>

jQuery Datepicker - Set 1st picker to limit to active week of 2nd picker

Two datepickers, staff are to enter a weekday into datepicker 1 (#from) and then enter in a second date into (#to). Date 2 must always be in the future with respect to date 1. Weekends not allowed.
working example of this, excluding weekends, and not allowing past dates in date 2, is available in this fiddle:
https://jsfiddle.net/gLrumpo3/6/
<input id="from">
<input id="to">
$("#from").datepicker({
defaultDate: new Date(),
minDate: new Date(),
beforeShowDay: $.datepicker.noWeekends,
onSelect: function(dateStr)
{
$("#to").val(dateStr);
$("#to").datepicker("option",{ minDate: new Date(dateStr)})
}
});
$('#to').datepicker({
defaultDate: new Date(),
beforeShowDay: $.datepicker.noWeekends,
onSelect: function(dateStr) {
toDate = new Date(dateStr);
fromDate = ConvertDateToShortDateString(fromDate);
toDate = ConvertDateToShortDateString(toDate);
}
});
Waht I need now though, is to be able to "lock" the 2nd date input to the same WEEK as the first date, I thought about ising maxDate, but I can only specifiy an arbitrary offset, like Xdays, or a specific date. This is no good as people may select thursday for example, i cant then add 4 days to it and set it as max date, as they would be able to select monday next week.
So how can i constrain their date inouts to one week, where that week is set absed on the day selected of the 1st field.
Please update fiddle with working answers if possible. Thanks.
Try this code
var date = $(this).datepicker('getDate');
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
$( "#to" ).datepicker("option",{minDate: new Date(dateStr), maxDate:endDate});
You can set maxDate to last date of that week for $( "#to" ) datepicker.
$("#from").datepicker({
defaultDate: new Date(),
minDate: new Date(),
beforeShowDay: $.datepicker.noWeekends,
onSelect: function(dateStr)
{
$("#to").val(dateStr);
var date = $(this).datepicker('getDate');
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
$( "#to" ).datepicker("option",{minDate: new Date(dateStr), maxDate:endDate});
}
});
$('#to').datepicker({
defaultDate: new Date(),
beforeShowDay: $.datepicker.noWeekends,
onSelect: function(dateStr) {
toDate = new Date(dateStr);
//fromDate = ConvertDateToShortDateString(fromDate);
//toDate = ConvertDateToShortDateString(toDate);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<input id="from">
<input id="to">

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

javascript calendar - highlight specific days

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

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