MooTools DatePicker
Will work for any date-format and even supports time-picking.
4 skins ready for download, and it's easy to skin it yourself.
(I just tried to create the best javascript datepicker available)
License
You can freely use this work - but some rights are reserved.Downloads
» Source code (for development)
Additional downloads
» Basic Skin - CSS only» Vista Skin - CSS & Images
» OSX Dashboard Skin - CSS & Images
» jQuery UI Skin - CSS & Images
Try the examples at the bottom of this page to check out the different skins!
GitHub
I am using a Git repository for code management. Feel free to contribute.Requirements
Requires MooTools Core v1.2+Tested on Firefox 3 (OSX, Win XP, Win Vista), Safari 3 (OSX, Win XP), Safari 4 beta (OSX), IE 7 (Win XP, Win Vista), IE 8 (Vista) and even IE6 (XP @ VirtualPC). Please help extend this list.
Usage
new DatePicker(input-target-selector [, options-object]);where the input-target-selector naturally is a MooTools selector (eg. .datepickers or #great_picker). The datepicker will be effective for all selected input elements. Usage examples are given at the bottom of this document.
Usage with Ajax
When loading content by Ajax after creating the DatePicker instance, simply re-scan the DatePicker targets by calling attach(), for example:my_datepicker.attach();
Using the Skins
Just include the CSS file of a skin, and specify the datepicker class (pickerClass) through your datepicker options. I recommend putting all skin files in one subfolder on your filesystem. Since image-locations are stored as relative paths in CSS, the images will work out of the box.Options
| Option | Default value | Description |
|---|---|---|
| pickerClass | datepicker | CSS class for the main datepicker container element. |
| toggleElements | null | Toggle your datepicker by clicking another element. Specify as a MooTools selector. The resulting elements are mapped to the selected datepickers by index (the 1st toggle works for the 1st input, the 2nd toggle works for the 2nd input, etc.) |
| days | ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] | Labels for the days, allows for localization. |
| dayShort | 2 | Length of day-abbreviations used in the datepicker. |
| months | ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] | Labels for the months, allows for localization. |
| monthShort | 3 | Length of month-abbreviations used in the datepicker. |
| startDay | 1 | First day of a week. Can be 0 (Sunday) through 6 (Saturday) - be aware that this may affect your layout, since days in the last column will likely have a style with right-margin: 0px;which would need to be applied to a different day. Default value 1 is Monday. |
| timePicker | false | Enable/disable timepicker functionality. See timepicker example below. Hours/Minutes values can be changed using the scrollwheel. |
| timePickerOnly | false | (v1.16+) set to true to use datepicker for time-selection only; recommended formatis H:i; will automatically force timePicker and startView options into timepicker mode |
| yearPicker | true | Enable/disable yearpicker functionality. Makes it much easier to change years. |
| yearsPerPage | 20 | Amount of years to show in the year-picking view. Be aware that this may affect your layout. |
| format | d-m-Y | Visible date format. Does not affect the actual output when your form is submitted (refer to the inputOutputFormat for that). Supported format symbols are described in the "Dateformatting" section. |
| inputOutputFormat | U | Define how the input value of the original datepicker input element is interpreted. After selecting a date, it's value will be again formatted in this format. Refer to the "input/output format" example. The default value U is a Unix-timestamp. Supported format symbols are described in the "Dateformatting" section. For example: to use MySQL dates 1-on-1 simply set Y/m/d. If you encounter problems with your formatting, try enabling the debug option, it will alert date-parsing errors. |
| animationDuration | 400 | Duration of the slide/fade animations in milliseconds. |
| useFadeInOut | true (false on Internet Explorer) | Whether to fade-in/out the datepicker popup. |
| startView | month | Initial view of the datepicker. Allowed values are: time(only when timePicker option is true), month,year, decades |
| allowEmpty | false | When set to true the datepicker intializes empty when no value was set (instead of starting at today). In addition the backspace- and delete-key will remove a value from the input. Check out the Allow empty example below. |
| positionOffset | { x: 0, y: 0 } | Allows you to tweak the position at which the datepicker appears, relative to the input element. Formatted as an object with x and y properties. Values can be negative. |
| minDate | null | Minimum date allowed to pick. Blocks anything before. Formatted as an object with a date and format property, which allows specification in any format you want. Example: { date: '10-03-2009', format: 'd-m-Y' } or { date: '2009/11/28', format: 'Y/m/d' } |
| maxDate | null | Maximum date allowed to pick. See minDate. |
| debug | false | When enabled, will not hide the original input element. Additionally, any formatting errors will be alerted to the user. |
| onShow | $empty | Event hook triggered when the datepicker pops up. |
| onClose | $empty | Event hook triggered after the datepicker is closed (destroyed). |
| onSelect | $empty | Event hook triggered when a date is selected. (v1.16+: comes with 1 argument, a standard javascript Date object representing the selected Date) |
Requested/planned features
- Support for date-range picking
- Prepare for MooTools 1.3 (2.0?) (personal todo)
Date-formatting
The date-formatting functions featured in the DatePicker support basic PHP date-format syntax. Supported symbols are listed below. Unsupported symbols will just be output as provided. To use the supported symbols literally, escape them with a \.
- y - Two digit representation of a year
- Y - Four digit representation of a year
- m - Numeric representation of a month, with leading zeros
- n - Numeric representation of a month, without leading zeros
- M - A short textual representation of a month, three letters
- F - A full textual representation of a month, such as January or March
- d - Day of the month, 2 digits with leading zeros
- j - Day of the month without leading zeros
- D - A textual representation of a day, three letters
- l - A full textual representation of the day of the week
- G - 24-hour format of an hour without leading zeros
- H - 24-hour format of an hour with leading zeros
- g - 12-hour format of an hour without leading zeros
- h - 12-hour format of an hour with leading zeros
- a - Lowercase Ante meridiem and Post meridiem
- A - Uppercase Ante meridiem and Post meridiem
- i - Minutes with leading zeros
- s - Seconds, with leading zeros
- U - Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
Creating your own skin
The Datepicker generates very clean XHTML, with many class-hooks for CSS. Refer to the existing skins for a speed-start. Some notes:- The previous, next and close elements have textual contents («, », x) by default; as done in the additional skins, these can be hidden using (for example) text-indent: -999px style
- The body element has 1 unclassed child, which in turn has 2 unclassed children. These are used for animation, and should be ignored. Their styles are based on the body class and should have no influence on the rendering of your datepicker. Just imagine the body element directly contains either the years, months, days or time class.
- The class selected is added to the date/month/year representing the current value.
- The class unavailable is added to any date/month/year which is outside the configured range (using the minDate and maxDate options).
- Every day element also has a day0 ... day6 class added, indicating which day of the week it is (0 being Sunday through 6 being Saturday).
- Every week element also has a week0 ... week5 class added, indicating which row of weeks it is (there is always 6 weeks displayed).
- Every month element also has a month1 ... month12 class added, indicating which month of the year it is.
- Every year element also has a yearX class added, where X simply is the index of the displayed year (0 being the first year).
Examples
Skins
Some basic examples, showing the use of different skins.» view code
Javascript
window.addEvent('load', function() {
new DatePicker('.demo_vista', { pickerClass: 'datepicker_vista' });
new DatePicker('.demo_dashboard', { pickerClass: 'datepicker_dashboard' });
new DatePicker('.demo_jqui', { pickerClass: 'datepicker_jqui', positionOffset: { x: 0, y: 5 } });
new DatePicker('.demo', { positionOffset: { x: 0, y: 5 }});
});HTML
<label>Datepicker with Vista skin:</label> <input name='date_B' type='text' value='' class='date demo_vista' /> <label>Datepicker with OSX Dashboard skin:</label> <input name='date_B' type='text' value='' class='date demo_dashboard' /> <label>Datepicker with jQuery UI skin:</label> <input name='date_B' type='text' value='' class='date demo_jqui' /> <label>Datepicker basic (CSS only):</label> <input name='date_B' type='text' value='' class='date demo' />
CSS
input.date {
width: 150px;
color: #000;
}Yearpicking / Timepicking
Two examples that show how you can enable or disable yearpicking and timepicking.» view code
Javascript
window.addEvent('load', function() {
new DatePicker('.demo_noyear', { pickerClass: 'datepicker_vista', yearPicker: false });
new DatePicker('.demo_time', { pickerClass: 'datepicker_vista', timePicker: true, format: 'd-m-Y @ H:i' });
});HTML
<label>Datepicker without yearpicker:</label> <input name='date_B' type='text' value='' class='date demo_noyear' /> <label>Datepicker with timepicker (use mousewheel to change time):</label> <input name='date_B' type='text' value='' class='date demo_time' />
Allow empty
Allowing no value by setting the allowEmpty option to true. Press backspace or delete to clear the selected date again.» view code
Javascript
window.addEvent('load', function() {
new DatePicker('.demo_allow_empty', {
pickerClass: 'datepicker_dashboard',
allowEmpty: true
});
});HTML
<label>Datepicker starting at and allowing no value:</label> <input name='date_allow_empty' type='text' value='' class='date demo_allow_empty' />
Toggle by Element
Toggle the DatePicker through a separate element. Click the calendar icon.
» view code
Javascript
window.addEvent('load', function() {
new DatePicker('.date_toggled', {
pickerClass: 'datepicker_dashboard',
allowEmpty: true,
toggleElements: '.date_toggler'
});
});HTML
<input name='date_toggled' type='text' value='' class='date date_toggled' style='display: inline' /> <img src='img/calendar.gif' class='date_toggler' style='position: relative; top: 3px; margin-left: 4px;' />
Restricted date-range
An example showing how you can restrict the input range of dates.
» view code
Javascript
window.addEvent('load', function() {
new DatePicker('.demo_ranged', {
pickerClass: 'datepicker_vista',
inputOutputFormat: 'd-m-Y',
yearPicker: false,
minDate: { date: '10-03-2009', format: 'd-m-Y' },
maxDate: { date: '25-06-2009', format: 'd-m-Y' }
});
});HTML
<label>Datepicker restricted to dates between 10-03-2009 and 25-06-2009:</label> <input name='date_B' type='text' value='20-03-2009' class='date demo_ranged' />
Starting value (input/output value)
These examples show how you can set the starting value by simply putting it in your original value tag. Additionally, you may use the option inputOutputFormat to specify how to interpret this value, and how it will be output again after picking a date.
Please note: The debug option is enabled which will show you the original input and its actual value (the first input element), which is normally hidden. The second input element is the datepicker.
» view code
Javascript
window.addEvent('load', function() {
new DatePicker('.demo_value', {
pickerClass: 'datepicker_jqui',
debug: true
});
new DatePicker('.demo_value2', {
pickerClass: 'datepicker_jqui',
inputOutputFormat: 'Y/m/d',
debug: true
});
});
HTML
<label>Datepicker starting at Unix-timestamp 1234567890 (14th of Februari 2009):</label> <input name='date_B' type='text' value='1234567890' class='date demo_value' /> <label>Datepicker starting at 2009/06/24 (to read as 'Y/m/d'):</label> <input name='date_B' type='text' value='2009/06/24' class='date demo_value2' />
Localized Month/Day labels
This example shows how simple it is to change the month/day labels in another language.
» view code
Javascript
window.addEvent('load', function() {
new DatePicker('.demo_dutch', {
pickerClass: 'datepicker_dashboard',
days: ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'],
months: ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'October', 'November', 'December']
});
});HTML
<label>Datepicker with Dutch labels:</label> <input name='date_B' type='text' value='' class='date demo_dutch' />



Comments (146)
I tried to get the DatePicker running with FormCheck, but was not successfull. Standalone (without your code) FormCheck worked, but with your DatePicker, FormCheck didn't work anymore.
I tracked this down to FormCheck also doing validation on the original input field (even though set to "display: none"). I fixed this by modifying FormCheck not to validate elements that are "display: none".
--
Martin
Second time I have needed a datepicker and timepicker in one. Thank you very much.
Is there a way to set the value of the field to a specific timestamp? so if I check a check box somewhere:
var picker = new DatePicker('.demo_vista', { pickerClass: 'datepicker_vista', timePicker: true, format: 'Y-m-d H:i:s' });
//var started is the checkbox;
started.addEvent('change', function() {
usertime.set('value', '1242763047');
});
Great documentation too.
Maybe in the future ? :-)
Is there a way to set the date via javascript? I tried the DatePicker.select method, but this doesn't work if the date input hasn't had focus. The onFocus event sets the this.input and this.vsiual properties which are used in the select method.
var val ='2009-07-05' ;
var formatted_val =cal.format (
new Date (cal.unformat (val, cal.options.inputOutputFormat)),
cal.options.format
) ;
$('myinput').value =val ;
$('myinput').getNext ().value =formatted_val ;
Hope that helps,
I used a similar workaround, but the getNext() increases the coupling with the DOM. If the position of the sibling element in the DOM changes somehow (which is not unthinkable imho) you're screwed. I was really looking for a somewhat more elegant solutions, but couldn't found one without some serious refactoring of the DatePicker class.
onShow: function() {
if (Browser.Engine.trident4) $$('select').setStyle('visibility', 'hidden');
}
onClose: function() {
if (Browser.Engine.trident4) $$('select').setStyle('visibility', '');
}
I consider making this part of the official release. Any thoughts?
Right, that seems good, I just worry about the users being frightened that the inputs are disappearing. I ended up just moving it to the right which will do for now. Mostly, I will try to convince them to upgrade their browser.
I think you could add it in to the next release, but as an option not as a default.
Thanks so much for your help,
Matt
datepicker = new DatePicker(".datefield",{ pickerClass: 'datepicker_vista', startDay: 0,
onShow:function(){
datepicker.IframeShim = new IframeShim(datepicker.picker).show();
},onClose:function(){
datepicker.IframeShim.destroy();
}
});
A Calendar I'd so much like to match with mootools is here:
http://www.jboss.org/file-access/default/members/jbossrichfaces/freezone/docs/devguide/en/html/rich_calendar.html
I'd like to add this functionality if you are too busy?
By the way: I wasn't suggesting matching the whole functionality of the jBoss date picker in my previous posting; simply the week number).
so, if I have two of them, I could hook them together so dateA is always before dateB
thanks for sharing this, it's one of the best pickers I've tried (and I've tried LOTS)
Excelent script! Works like a charm.
I've been trying to set te minDate propertie of an input acording to the selected date of another. For example, to pick the check in and check out dates of a hotel. For example, if I pick 2009-08-08 for the check in, automatically set that date as the minDate for the checkOut (maybe, plus X days).
I've been trying with the onShow or onClose events, but I can't make it works. Could you help me?
Thanks in advance :)
Do you have any RSS thread (Datepicker only) which we can link to, to get latest update as soon as there is one ?
Also, do you have any change log to see improvements from one version to an other ?
Some ideas of improvements:
-Possibility to place it in line (always shown).
-Possibility to drag it.
I'd like to add this :
It would be great to allow one to change the minDate dynamically. I use 2 datepicker (start date and end date). When i select the start date, i'd like the end date to auto ajust to the start date AND the datepicker not to allow dates before the start date.
Hope you understand. I guess i could do it by recreating an instance of DatePicker onSelect of the first one.
Again, thanks for this tool!
Thanks
Is it possible to have the calendar inline (always displayed) above the input element?
Is it possible to start the calendar in decades mode, then month, then date?
If anyone could answer this question, or build a calendar that can ;) I would greatly appreciate it!
17.5kb as minified really doesn't justify its use for me though. Possible just needs a different way to compress it? I tried bananascript dot com and got it down to 6kb. You might want to dish that out as the minified versin with an explanation of what charset to use on the script include :))
something like :
var picker = new DatePicker(myElement,{....});
How can i empty the box after declaration with javascript?
How can i take the value of input box with javascript to control?
Some ideas (sent by mail + 1 new) :
-(new !) Add the possibility to show week numbers on each week line.
-Auto-date update two datepickers according to the value of one-another :
on minDate update, if stopdate's currently selected date < minDate then stopedate's currently selected date = minDate.
Same for max date
on maxDate update, if stopdate's currently selected date > maxDate then stopedate's currently selected date = maxDate.
Some problems i encoutered :
-When i configured mindate with current time. Current day wasn't selectable. I had to clearTime() so that current day would be selectable.
-My "value input" START_DATE was empty after creating the DatePicker. It would be great that upon creation of a datepicker on an input (here, what i call the "value input"), IF that input is empty then either the date input is also empty or the value input is filled with the date input value. Maybe this could be set up using options ?
-I tried to access $$('input[name=START_DATE]').retrieve('datepicker'). That was unsuccessful. Is it normal ? do i have to do something particular ? I thought it was logical that the datepicker would be attached to the input by default.
-Make it possible to specify minDate: 'today'. I think this is something alot of people would use.
Always and forever : thanks for this tool !
Other than that, it's very nice.
var oDatePicker = new DatePicker(oDate,{
format: 'd-m-Y',
toggleElements: '#DateResume',
});
#DateResume is a SPAN containing the date.
oDate is an input[type=hidden]
1-The DatePicker doesn't auto-update the span, have to do it onSelect.
2-The DatePicker appears in the top left corner instead of under the SPAN (i suppose it's cause it can't find the input)
Thanks again
Also when the page loads the current date time shows, but the 'value' is empty if the form is submitted. So, how can I set the value and have the format correct? Hope this is clear.
Using in a script section called via body=onload():
---------------------------------------------------
mydatepicker = new DatePicker('.demo_time', { pickerClass: 'datepicker_vista', timePicker: true, format: 'd-m-Y @ H:i' });
And this in the form:
---------------------
<input name='mydate' type='text' value='$context{dt}' class='date demo_time' />
The html is built in a Perl script to show $context{dt} becomes initialized with a time that was previously submitted. That value would be something like: 1249544543 . Would also like to change this value with javascript and have the format correct.
Any thoughts? Thanks.
How can i empty the box after declaration with javascript?
How can i set and get the value of input box with javascript to control?
Take a look at the workaround Cyrille (05-07-2009, 16:57) described. It isn't a very elegant/safe solution, but as far as I know the only one available.
If your main input is invisible (display none or type hidden) the picker won't appear in IE7 and will be displayed at the top left corner in FF 3.5
To solved this i changed the code like that:
line 148
- this.onFocus(item, clone);
+ this.onFocus(item, clone, togglers[index]);
line 177-178
- onFocus: function(original_input, visual_input) {
- var init_visual_date, d = visual_input.getCoordinates();
+ onFocus: function(original_input, visual_input) {
+ var init_visual_date, d = ($defined(toggler) ? toggler:visual_input).getCoordinates();
Hope this helps
line 177
- onFocus: function(original_input, visual_input) {
+ onFocus: function(original_input, visual_input, toggler) {
sry for the 2nd post
// this will change the value of the form field
// but will not update the display
form.datefield.value=1249621200;
I need a way to update the value and display of a date field.
my_datepicker.attach();
to attach the datepicker in the ajax form so that it will work?
i have 2 questions: i'm trying to set the date and time for an update form. i've set the value of my textbox field to:
value='27/08/2009 @ 15:00'
and the format to:
format: 'd/m/Y @ H:i',
but when the page loads, the date sticks but the time updates to the system time of my machine!
the 2nd question is i like to disable the form fields (to restrict users typing incorrect dates and then having to validate them) but i'm a asp.net user meaning i can access the form field when the page is submitted...
i usually use a hidden field to store the values of disabled fields, but how do i pass the date/time value to this field?
any info you can provide would be awusm,
cheers,
jake
onSelect: function(d) {
$('hidden_field').value = d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":00";
}
but still cant get the form fields to load the time correctly? i've tried every format i can think off...
cheers,
jake
format: 'd/m/Y @ H:i'
and:
inputOutputFormat: 'd/m/Y @ H:i'
works a treat ;)
In case anybody needed this, I am using the script on an input with a label related to its id, so i modified it a bit to assign the id to the clone and remove it from the original input. Starting line 130 of the uncompressed script.
var display = item.getStyle('display');
var originalID = item.getProperty('id');
var clone = item
.setStyle('display', this.options.debug ? display : 'none')
.store('datepicker', true) // to prevent double attachment...
.removeProperty('id')
.clone()
.store('datepicker', true) // ...even for the clone (!)
.removeProperty('name') // secure clean (form)submission
.setProperty('id', originalID)
.setStyle('display', display)
.set('value', init_clone_val)
.inject(item, 'after');
Cheers!
window.addEvent('load', function() {
new DatePicker('.demo_vista', { pickerClass: 'datepicker_vista',inputOutputFormat: 'm/d/Y',debug: true });
});
Filed input must be m/d/Y and it must display like that and write to the database like that. But while it writes to the database ok...and displays ok...the hidden field ALWAYS displays the wrong date...it jumps ahead one month? So if I input 09/03/2009 the hidden field will display 03-10-2009 and have that date selected on the pop up calendar? How do I make it pick the right date?
Anyway...I think Jake was onto something....with
onSelect: function(d) {
$('hidden_field').value = d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":00";
}
But being a javascript weakling...I don't know how to implement it or adapt it?
Anyone help?
If you start with the date 08/31/2009 and click on the calendar then click the right arrow to go to the next month it goes to October instead of September!
Can this be fixed?
May I suggest you add the following to the CSS so the Picker layout won't be affected by any existing CSS:
.datepicker .header {
margin: 0;
padding: 0;
background: none;
[...]
}
In my case I had already a .header class with some margin, padding and background set which led to layout problems in the Picker.
Cheers.
we made a keyboard navigable version of this script :
http://www.fri-dev.com/index.php?post/2009/09/04/Monkey-Physics-datepicker-%3A-keyboard-navigation-fix
Iam not sure if this is bug or something Iam doing is wrong
Can i make offer for you datepicker: when i attach image for toggle calendar way text field lost action on Focus event for show calendar instance? It mast be work too.
they click very often at the arrows ...
It is sadly a killer argument in much projects :(
May you change the number of the year and month with a select-box and if the time-picker is enabled you add the timepicker (smaller) at top of the chooser instead of adding the second step.
Grettings from Germany
}.bind(this));
On the new line 174, add
//save reference to clone for later use
this.clone = clone;
Then add the following code after
}.bind(this));
},
(so on line 178 that is)
refresh: function(){
$$(this.attachTo).each(function(item) {
// determine starting value(s)
if ($chk(item.get('value'))) {
var init_clone_val = this.format(new Date(this.unformat(item.get('value'), this.options.inputOutputFormat)), this.options.format);
} else if (!this.options.allowEmpty) {
var init_clone_val = this.format(new Date(), this.options.format);
} else {
var init_clone_val = '';
}
this.clone.set('value', init_clone_val);
}.bind(this))
},
Now you can set the new UNIX timestamp in your own input/select, and call the refresh function of the DatePicker.
I'm using your CSS based date picker. I'm using CSS with basic skin. but I see some special characters («) for previous and next buttons.
Also the width of the title (month year, next button, close button) doesn't extend fully.
Also i see some blank space between border and calendar. I'm using IE7. When i run the demo from this website it works fine. But when I refer to downloaded files datepicker.js and above CSS...it is little off..
Have the InvalidWeekDays implemented??? or setDisabledWeekDays, this i found in CalendaPopup.JS, is very usefull.http://www.mattkruse.com/javascript/calendarpopup/index.html
I almost have it working but encountered what I think is a bug. My inputOutputFormat is "n/j/y". If the date that is passed in looks like "9/12/09", datetimepicker.js will throw an error that it cannot format the year. I believe this is because your regex matches the "1" in "12", and therefore thinks the chunk to match against "y" is "/09" rather than "09".
My temporary workaround is to reverse the order of the regex like "3[01]|[12][0-9]|[1-9]" instead of "[1-9]|3[01]|[12][0-9]" so that it picks the biggest match first.
Not sure if this is the best solution, but thought you might want to know about a possible bug.
Otherwise, great job and thanks for the tool!
Thanks for the great tool!!
We are using the datepicker in our .net 3.5 website project there is a need to disable some of the dates on the calendar depending on the selection in a dropdownlist server control.
I have never worked with mootools
Please help!!!
how can i set the current date into the input box onshow
my workaround (it is very dirty^^):
datepicker.visual.set('value', datepicker.format(datepicker.d, datepicker.options.inputOutputFormat));
is there a more simply way?
i can't change the input-field-value from outside after it is bind on datepicker
example $('id_input_field').value='';
When I set a Datepicker in the page, the visible value in the text field is right (today's date). But if I submit the form that has the Datepicker in it, without changing the default values, the form field comes out blank? If I change the value, everything gets submitted the right way.
Any suggestions?
In FF3.5/Opera 10 works like a charm
var cal = $$('.datepicker_vista')[0];
var screenHeight = window.getSize().y;
var screenBottom = window.getScroll().y+screenHeight;
var calendarHeight = cal.getSize().y;
var calendarBottom = cal.getPosition().y+calendarHeight;
if(calendarBottom>screenBottom){
var newY = calendarBottom+10-screenHeight;
window.scrollTo(0,newY);
}
Also, for birthday pickers, it's nice to hide the year in the title. So I added an option for that:
if(this.options.hideYear){
this.picker.getElement('.titleText').set('text',this.options.months[month]);
}else{
this.picker.getElement('.titleText').set('text',this.options.months[month]+' '+this.d.getFullYear());
}
And last, although your documentation and your example show minDate and maxDate to be inclusive, when I try it on my own page it's exclusive. Any thoughts offhand? I can send you the code if you want to pm me. The page isn't live yet.
Thanks,
Bob
Hi there!
VERY nice Datepicker - best i've ever seen and i wanted to include it into my (under development) CSS-Frame Layout you can find over at http://www.artness.de/area/.
Two "Bugs" i am fighting with are:
In IE the Datepicker will "hide" all DIVs and display only itself. All Div's reveal again if the datepicker ist closed.
To workaround this strange behaviour, i needed to inject() it inside the DIV where the toggler (input field) is placed.
The 2nd Problem is, that the screen position is calculated absolutely + scrolled offset.
The DIV the datepicker toggler is located in, is scrollable so the screen itself stay where it is but the div with the toggler scrolls. The result is, that the datepicker will not display right below the toggler but somewhere else.
Is there any chance of a workaround or a fix .. like some extra option to setup the target the picker should be injected to:
options: { injectTarget : false }
this.picker = new Element('div', { 'class': this.options.pickerClass }).inject(this.options.injectTarget ? this.options.injectTarget : document.body);
and 2ndly to have an option on how to place the datepicker - if the whole page is scrolled, everything is fine but if a scrollable div is scrolled, the repositioning fails ...
sorry for my english - it's not my mother tongue though.
Keep up the excellent work
my date still formatted (05-10-2009) in the input text..
my setting:
<pre>
inputOutputFormat: 'd/m/Y',
</pre>
and html
<code>
<input size="30" value="05/10/2009" class="date date_pick" type="text"></code>
i hve set the value is current date..
please help.. thanks
setMinDate: function(smindate, sformat) {
this.options.minDate = this.unformat(smindate, sformat);
this.options.minDate.setHours(0);
this.options.minDate.setMinutes(0);
this.options.minDate.setSeconds(0);
this.options.minDate.setMilliseconds(0);
}
Also i would suggest initializing the minDate's hour, minute and seconds and even milliSeconds, so that date comparisons will be more accurate.
So the "formatMinMaxDates" function should be:
formatMinMaxDates: function() {
if (this.options.minDate && this.options.minDate.format) {
this.options.minDate = this.unformat(this.options.minDate.date, this.options.minDate.format);
this.options.minDate.setHours(0);
this.options.minDate.setMinutes(0);
this.options.minDate.setSeconds(0);
this.options.minDate.setMilliseconds(0);
}
if (this.options.maxDate && this.options.maxDate.format) {
this.options.maxDate = this.unformat(this.options.maxDate.date, this.options.maxDate.format);
this.options.maxDate.setHours(23);
this.options.maxDate.setMinutes(59);
this.options.maxDate.setSeconds(59);
this.options.maxDate.setMilliseconds(999);
}
}
Anyways, good work on this datepicker, works very well ! Thanks.
-Emil
This app looks great!!! I'm looking to replace my current date picker, I'd love to use this one but I was wondering whether its easily possible to separate the output in to 3 inputs/selects this is essential for the app its going into.
If its not possible I will look at writing the functionality into the datepicker if thats ok?
Please let me know!
Vince
Great components but it lacks the functionality to alter the value remotely via javascript...
I took the liberty and fixed this problem with the following solution:
I define an additional event for the original input element inside the attach() function of the class. (In my version of the script - which is 1.16 - this is line 143):
item.addEvent(\'change\', function(value) {
this.input = item;
this.visual = clone;
var d = new Date(this.unformat(value, this.options.inputOutputFormat));
this.select({ day: d.getDate(), month: d.getMonth(), year: d.getFullYear() });
}.bind(this));
After this you can change the value of the element by firing the change event, e.g.
$(\'mydatepicker\').fireEvent(\'change\', \'2009-10-23\');
Please make sure to set the inputOutputFormat property according to your date format!
Cheers and thanks for the component!
Pepe / Developer at www.groupion.com
The only thing I'd like to see implemented, is the option "zIndex": if you're using the picker in a modal window, it will be displayed behind it. It's just 1-2 lines of code to modify, I've did it to my copy and thought I'd share the idea.
Thanks again!
inputOutputFormat: \'Y/m/d\'
It\'s a really great little tool, Thank you.
I'd like to know if this script allow us to open the calendar directly when the mouse is over the form field ?
i don't want the users to have to click in the form field to open the calendar.
Can you tell me if it is possible ?
Thanks
Olivier
My input/output format is "Y-m-d", my display format is "F j, Y".
Dates in September, like "2009-09-17" are being formatted as "October 17, 2009", not "September 17, 2009".
I haven't figured out why. Seems to be happening only with dates September. All my September dates are being rendered as October.
But then if I use the datepicker to change the date, September is fine. This is only happening when the datepicker is initialized. It makes no sense.
No wonder it wasn't noticed before -- It will only happen on days like today (Oct 31) when you are initializing to a month which doesn't have this date (eg September 31, which doesn't exist).
line 711 in the "unformat" method, this line fails:
case 'n': d.setMonth(v - 1); break;
I can't change the date to September, because the current date is October 31 and there is no September 31. The method fails silently, and I end up with the wrong month.
To fix this, just add this before the "switch" on line 707:
d.setDate(1);
For general consumption, you might want more sophisticated logic, but that fixed my problem.
Cheers
- Make it work well with OverText (There are a few issues, which I suspect is due to the cloning of elements)
- Have it implement Events, and fire onShow / onClose events, rather than manually calling the functions (this allows multiple functions to be called onShow / onClose, and also allows adding of events nicely after the DatePicker object is created)
- Allow the picker to be manually shown and hidden externally (I know you can set a manual toggler on creation of the DatePicker, but this isn't very flexible)
- For ultimate customisation, instead of having manual "new Element("s everywhere, allow customization of the generated HTML. Maybe you could specify some sort of "default templates" and then populate these with generated data? (All I was personally after was changing the symbol for moving left and right in months, but the HTML template route seems like it could then handle practically every possible customization.)
- Add an option to add a \"Skip\" button to the time picker.
- When firing the event \"onClose\", pass along an object with details of the selected time: i.e. the time itself and whether \"Skip\" was pressed in the suggestion above
The reason the above would be useful is that for an events calendar, whether a time is needed may be event-dependent. Also: on selection of the date / time, there may have to be some code to deal with whether the user want to specify a time or not.
The div that contains the picker needs a z-index, i tried getting the calender to work on a page that had a background div and it took me some time to figure out why it wouldn't show.
Sure one could argue it's IE's fault, but it's a bug no matter how you put it, and can be easily mended if you use
Date.getFullYear().toString().substring(2);
Date.getYear() is obsolete, please don't use it. :)
One 'bug' or at least strange behavior. When I load the full moretools, the minDate and maxDate fields break functionality. Without those two, everything works fine.
I've just noticed something wrong (t.tostring()) in the unformat function and Mootools 1.2.4 when option mindate is set...
the refresh function by Rekcor is not free of bugs. The clone is saved in the main DatePicker-objekt, but you have to save it in the attachTo-Objects to get right results if you have more than one Date-Field.
So change :
this.clone = clone; => this.attachTo[index].clone = clone;
this.clone.set('value', init_clone_val); => item.clone.set('value', init_clone_val);
After implementing some stuff using Mootools more, our datepickers failed to work. I eventually tracked it down to a problem in formatMinMaxDates() - the date extentions has added a Date.format() function to native date objects, so the test to see whether this.options.minDate/maxDate was a Date always assumed it wasn't a date. - Lines 91 & 94. Here's the fix I put in place: Beginning at line 90: formatMinMaxDates: function() { if (this.options.minDate && $type(this.options.minDate) != 'date') { this.options.minDate = this.unformat(this.options.minDate.date, this.options.minDate.format); } if (this.options.maxDate && $type(this.options.maxDate) != 'date') { this.options.maxDate = this.unformat(this.options.maxDate.date, this.options.maxDate.format); this.options.maxDate.setHours(23); this.options.maxDate.setMinutes(59); this.options.maxDate.setSeconds(59); } } Best wishes, Craig
or cancel
After implementing some stuff using Mootools more, our datepickers failed to work.
I eventually tracked it down to a problem in formatMinMaxDates() - the date extentions has added a Date.format() function to native date objects, so the test to see whether this.options.minDate/maxDate was a Date always assumed it wasn't a date. - Lines 91 & 94.
Here's the fix I put in place:
Beginning at line 90:
formatMinMaxDates: function() {
if (this.options.minDate && $type(this.options.minDate) != 'date') {
this.options.minDate = this.unformat(this.options.minDate.date, this.options.minDate.format);
}
if (this.options.maxDate && $type(this.options.maxDate) != 'date') {
this.options.maxDate = this.unformat(this.options.maxDate.date, this.options.maxDate.format);
this.options.maxDate.setHours(23);
this.options.maxDate.setMinutes(59);
this.options.maxDate.setSeconds(59);
}
}
Hope this helps!
Craig
On line 625 we have:
# case 'y': f += (100 + t.getYear() + '').substring(1); break
It is returning 109 instead of 09
I replaced that with this to fix the problem:
# case 'y': f += (t.getFullYear() + '').substring(2); break;
Regards,
Ivan
Ihave one suggestion. It would be nice that you could type de date manually.
For some reason, the last row of dates doesn't show up. For example, in March 2009, the last visible row is 23-29 which means 30 and 31 aren't selectable. Your thoughts?
I fixed a glitch with the min/max month being one month off in renderYear.
Instead of "... +1 < ..:" and "... -1 > ..."
maybe "... <= ..." and "... >= ... + 1" is clearer.
I hope the pasting code works:
limited: function(type) {
var cs = $chk(this.options.minDate) && this.options.minDate;
var ce = $chk(this.options.maxDate) && this.options.maxDate;
if (!cs && !ce) return false;
var cc = this.d;
switch (type) {
case 'year':
return (cs && cc.getFullYear() < cs.getFullYear()) ||
(ce && cc.getFullYear() > ce.getFullYear());
case 'month':
return (cs && cc.getFullYear()*12+cc.getMonth()+1 < cs.getFullYear()*12+cs.getMonth()) ||
(ce && cc.getFullYear()*12+cc.getMonth()-1 > ce.getFullYear()*12+cs.getMonth());
case 'date':
return (cs && cc < cs) || (ce && cc > ce);
}
},
Playing with the CSS, I've found a simple workaround. I changed the height of the days. For whatever reason, IE renders them differently and there isn't enough space for the last row to show up on the fixed size background. Here's what worked for me (looks ok on other browsers - just a little extra space at the bottom):
.datepicker_dashboard .days .day {
float: left;
text-align: center;
overflow: hidden;
width: 23px;
padding-top: 1px;
height: 12px; /* Modified by Jeff Ropp to deal with IE6 */
margin: 0 1px 1px 0;
}
but i had problem with value of original input. when one doesn't select anything, the original input stays clear, so when the form with date submits, the value i got is not a default value, but null.
so i added some improvements to your attach function:
...
// determine starting value(s)
if ($chk(item.get('value'))) {
...
} else if (!this.options.allowEmpty) {
..
var init_orig_val = this.format(new Date(), this.options.inputOutputFormat); // init original control to default value
item.set('value', init_orig_val);
} else {
...
i think you can include something live this in feature releases
I also suggest that instead of using your own date parser and formater, use Date.Extras in Mootools.More. This way you can focus solving more usability issues as they arise.
-----------------------------------------------------
<head>
<script type="text/javascript" src="mootools-1.2.4-core-jm.js"></script>
<script type="text/javascript" src="datepicker.js"></script>
<link rel="stylesheet" type='text/css' href='datepicker.css'>
<script type="text/javascript">
window.addEvent('load', function() {
new DatePicker('.demo_ranged', {
pickerClass: 'datepicker',
inputOutputFormat: 'H:i',
timePicker: true,
timePickerOnly: true,
startView: 'time'
});
});
</script>
</head>
<body>
<input name='time' type='text' value='' class='date demo_ranged' /></body>
</html>
We also needed users to be able to manually enter their own dates and search on those, so we modified the addEvents on the clone as follows, which obviously enables user input and marries up entered changes with the hidden text box:
else {clone.addEvents({
'keydown': function(e) {
if (e.key == "tab") {
this.close(null,true); }}.bind(this),
'focus':function(e){ this.onFocus(item, clone);
}.bind(this),
'keyup':function(e){ this.input.set('value', this.visual.get('value')); }.bind(this)
}
thanks and best wishes
very nice work.
Is it possible to show specific start-day other than today or value in textbox??
Thanks
Alfred
I dont know if anyone could help me, but im completely stuck.
I have been dealing with this error for DAYS. And cant find a solution.
Every time a click a get the error: this.picker is null (line 36 of datepicker.js)
It has something to do with the usage of the jquery library im using for input validation scripts, because I just made a quick simple page where there is just the input for the datepicker, and it works fine. But when i import the jquery library it gives that error.
Using firefox/safari is not a big deal, because the website works OK, but using IE is not. You can not move the side bar of the browser and also the rest of javascript does not work as they do in other browser, because every time a click does not matter where, it gives the this.picker is null error. (On Safari it says: 'this.picker [null]' is not an object
I just hope there is someone that could help me, because im just going crazy....
Thank you!!!
Thanks
this is simply nice. But I am having trouble to get it work. Sorry I am real dummy in javascript, but this should not be so difficult to implement. I am getting following error when trying to copy code from examples
"DatePicker is not a constructor"
Could someone advice pleaaase?
my code includes following:
<link href="datepicker_dashboard.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/mootools.js"></script>
<script type="text/javascript" src="datepicker.js"></script>
</head>
<body>
<script type="text/javascript">
window.addEvent('load', function() {
new DatePicker('.date_toggled', {
pickerClass: 'datepicker_dashboard',
allowEmpty: true,
toggleElements: '.date_toggler'
});
});
</script>
<input name='date_B' type='text' value='' class='date demo_dashboard' />
for those, like me, who have to use a language with accented characters, here is a simple workaround for labels :
1- convert your character to unicode, here for example
http://people.w3.org/rishida/scripts/uniview/conversion.php
2 - insert it in the list of, say, months, like :
months: ['Janvier', 'F\u00E9vrier', etc ..
Thats it.
Thanks for this script, it looks and works great. I have 2 suggestions that I think would make the script perfect.
1. A way to spread the values across multiple inputs e.g. I could have 3 drop-downs, one for day, one for month and one for year. Updating the calendar updates the selected values in the 3 drop-downs but it also allows the user to change a date value without using the calendar. This would be very usefull for when javascript is not available.
2. When you use togglebyelement and then change the text in the textbox the output value is not updated.
I hope you consider implementing my ideas .
Thanks
Nigel
with Best Regards
Lev
if somebody has a version with the zindex can you send it? thank you in advance
z-index: 9999;
or the number that you need..
;)
Example:
"the javascript"
myDatePicker = new DatePicker('.demo_value', {
pickerClass: 'datepicker_jqui'
});
myDatePicker.onFocus($('theId'),$('theId').getNext());
"the html"
<input type="text" name="some_name" class="demo_value" id="theId" />
That´s all ! ! ! !
I hope you find this usefull.
Sorry for my low level English ;)
"2. When you use togglebyelement and then change the text in the textbox the output value is not updated."
This is essential! Now my users mistakenly think that they can alter the date by changing the text in the textbox. Please fix this soon!
Brilliant picker otherwise. :-)
"Attribution — You must attribute the work in the manner specified by the author or licensor"
How?
"DatePicker is not a constructor"
Can anyone help?
A simple problem.
The app works fine, I was able to change the date format to match that expected of MySQL. However I am having a bit of a problem with the post data.
When the date is posted it comes up as number, eg. Date selected - 2010-01-28 and the value 1262881619 gets posted. What am I doing wrong???? Or not Doing???
just notice...
you have a small bug in the functions next() and previous()
else if (this.mode == 'month') {
this.d.setMonth(this.d.getMonth() - 1);
}
should be
else if (this.mode == 'month') {
this.d.setDate(1);
this.d.setMonth(this.d.getMonth() - 1);
}
to fix next() and previous() actions from the end of the month to next month.
i.e. from 2010-01-30 -> next month ;-)
If I set 1 January 2009 (or any year) to be the minimum date, then you cannot select the 1st. The minimum is actually 2 January!
Just wanted to say I've been reviewing all the comments above and have applied all the bug fixes that I could replicate from recent comments. Please see my forked instance of the code in git repo here: http://github.com/MadmanMonty/mootools-datepicker
See the wiki page for notes on changes.
Credit to marfillaster for some of the major code updates.
If you spot any issues with my instance feel free to use the issues section in github and I'll attempt to review and resolve.
I hope these updates help some of you. Enjoy.
I am doing this in Ajax
var fm = new Element('form', {'action': '#', 'method': 'post', 'id':'FormElement'}).injectAfter(document.id('InsertionID')); // Add A Form Element to put my injected foprm into
var sp = new Element('input', {'type': 'text' , 'class' : 'date UID_1234' , 'style' : 'display : inline', 'id': 'UID_1234','value':'20, Jan 2010'}).inject(document.id('FormElement'));
// New Input Element
var sp2 = new Element('img', {'src' : 'assets/calendar.gif', 'class': 'date_toggler', 'id' : 'clickdate', 'style' : 'position: relative; top: 3px; margin-left: 4px;'}).injectAfter(document.id('UID_1234'));// new Calendar IMG To Click Onto
x1 = new DatePicker('#UID_1234', {pickerClass: 'datepicker_dashboard', allowEmpty: false, toggleElements: '.date_toggler', inputOutputFormat: 'd, M Y', onClose: function(){updateAFieldByUID('UID_1234');}});
// Add The DatePicker Class to Get It All Working.
Now I can see by the activity in the DOM that another element is being cloned.
I am however seeing this cloned element and not mine.
And when I Select the value in the datePicker It merely puts it into its newly created element in a YYYY-MM-DD format and does not show me my element again.
I understand roughly how the class is working but can't see at what point things are be hidden an shown.
N
I cant seem to find how to implement this using the Options above.
Thanks
If i attach it to input with pre-defined value "31-03-2009", and CURRENT month is February, it becomes "03-03-2009".
Problem is in unformat function. You should set year and month as soon as possible (don't forget about leap years).
Something like this:
//modified - first of all set month and year
if (a['y']) d.setFullYear(a['y'] < 30 ? 2000 + a['y'].toInt() : 1900 + a['y'].toInt());
if (a['Y']) d.setFullYear(a['Y']);
if (a['m']) d.setMonth(a['m'] - 1);
if (a['n']) d.setMonth(a['n'] - 1);
if (a['M']) {
a['M'] = this.options.months.filter(function(item, index) { return item.substring(0,this.options.monthShort) == a['M'] }.bind(this))[0];
}
if (a['F']) d.setMonth(this.options.months.indexOf(a['F']));
for (c in a) {
var v = a[c];
switch(c) {
case 'y': d.setFullYear(v < 30 ? 2000 + v.toInt() : 1900 + v.toInt()); break; // assume between 1930 - 2029
case 'Y': d.setFullYear(v); break;
case 'm':
case 'n': d.setMonth(v - 1); break;
// FALL THROUGH NOTICE! "M" has no break, because "v" now is the full month (eg. 'February'), which will work with the next format "F":
-lenkey
When I pick date only, we have both date + current time in Unixtime stamp.
pickerClass: 'datepicker_dashboard',
format: 'd-m-Y',
timePicker: true,
allowEmpty: false
});
var reqNota = new Request({
url: '',
method: 'get',
onComplete: function(response){
$('inputdate').value= '1267117200';
}
});
<input name='inputdate' id='inputdate' type='text' class='date date_toggled' style='display: inline'/>
^^
your datepicker.js is workin fine.. but i got a problem when i want to set value on my datepicker inputdate.
on the onComplete request i got nothing on my input date change... :|
$('inputdate').value= '1267117200';
how to resolve this??? pls help me.. thanks...
the year is misformated : 01/03/110
instead of : 01/03/10
in the fonction format(t, format) :
"case 'y': f += (100 + t.getYear() + '').substring(1); break"
the method getYear() seems to be deprecated in javascript.
i tryed to replace with :
"case 'y': f += (t.getFullYear() + '').substring(2);break;"
and it's works fine.