Skip to content

Instantly share code, notes, and snippets.

@hughbris
Last active June 27, 2019 11:50
Show Gist options
  • Save hughbris/4815199651b53c1edebed5f99c67af76 to your computer and use it in GitHub Desktop.
Save hughbris/4815199651b53c1edebed5f99c67af76 to your computer and use it in GitHub Desktop.
Grav JQuery datepicker for date field
- name: birthdate
label: Date of Birth
type: text
classes: past lifespan dob datepicker pure-input-1-3
# default: "{{ date('-30years') }}"
size: small
placeholder: 'dd/mm/yyyy' #fallback only, JS resets this
novalidate: true
validate:
required: true
# max: "{{ date() }}"
# TODO: this needs date format to language setting
jQuery(document).ready(function($) {
$('form').attr('novalidate','novalidate');
// this needs max and default set based on .dob/.past, .lifespan respectively; and date format to language setting
$('input.dob, input.past').attr('max', formatTimestamp(new Date(), 'YYYY-MM-DD'));
// TODO: adjust date format to locale
// *** Datepicker options
$('[type="date"],.datepicker').datepicker({
'autoSize': true,
'dateFormat': 'MM d, yy',
'firstDay': 1,
'showOn': 'focus',
'buttonImage': '/user/themes/themename/images/calendar-red.png', // this doesn't actually show now that I set readonly and showOn to 'focus' but I don't mind :)
'buttonImageOnly': true,
'beforeShow': function(el, dpo) {
},
'onSelect': function(dstr, dpo) {
// tricky/nasty but it works ...
this.removeAttribute('readonly');
this.setAttribute('value', dstr);
// console.log($(this).datepicker('getDate'));
this.setAttribute('data-machine-date', $(this).datepicker('getDate')); // $().data() doesn't work here .. true
$(this).change(); // needs to be explicitly triggered for dependent controls
this.setAttribute('readonly', 'readonly');
},
})
.attr('readonly', 'readonly')
.removeAttr('placeholder'); // because we don't need no placeholder when we have fancy JS
$('input.dob, input.lifespan').datepicker( "option", "defaultDate", '-30y');
$('.lifespan').datepicker( "option", {
'changeYear': true,
'changeMonth': true,
'minDate': '-120y',
'yearRange': '120:-0',
});
$('.past').datepicker( "option", "maxDate", 0);
$('.future').datepicker( "option", "minDate", 0);
});
Number.prototype.leadZeros = function(zeros) {
// returns a string with _zeros_ leading zeros
if ( this < Math.pow(10, zeros) ) {
var prefix = '';
for ( i = 1 ; i <= zeros ; i++ ) {
prefix += '0';
}
return prefix + this.toString();
}
else {
return this.toString();
}
}
function formatTimestamp(stamp, format) {
var year = stamp.getFullYear();
var month = (stamp.getMonth() + 1).leadZeros(1);
var dom = stamp.getDate().leadZeros(1);
switch(format) {
case 'YYYY-MM-DD':
return year + '-' + month + '-' + dom;
default:
return year + '-' + month + '-' + dom;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment