Skip to content

Instantly share code, notes, and snippets.

@nicolaracco
Created January 31, 2014 10:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolaracco/8729504 to your computer and use it in GitHub Desktop.
Save nicolaracco/8729504 to your computer and use it in GitHub Desktop.
Glue to allow you to work with date inputs using the native datepicker when supported and JQuery UI as a fallback
(function() {
var setupDatePickerGlue = function($el, format) {
var elName = $el.attr("name"), // field name
elId = $el.attr("id"), // field id
elValue = $el.attr("value"); // field raw value
// remove the name to prevent value conflict on submit
$el.removeAttr("name");
// prepend an hidden input field with the same name
$el.before($("<input type='hidden' name='" + elName + "' id='raw-" + elId + "' />"));
$el.datepicker();
// set the altField so we update the hidden input on date change
$el.datepicker("option", "altField", "#raw-" + elId);
// set the altFormat to update the altField with the given format
$el.datepicker("option", "altFormat", "yy-mm-dd");
// if there is a prefilled value, use it
if (elValue != null && elValue.length > 0) {
$el.datepicker("option", "dateFormat", "yy-mm-dd");
$el.datepicker("setDate", elValue);
}
// set the desired format
$el.datepicker("option", "dateFormat", format);
}
$(function() {
if (!Modernizr.inputtypes.date) {
$('input[type=date]').each(function() {
setupDatePickerGlue($(this), 'dd/mm/yy');
});
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment