Friday, 31 August 2012

Using the HTML5 date picker with backwards compatibility

If you didn't know, HTML5 introduced a new input type 'date' which allows the client to support it natively. Here is the native date picker in Chrome 21.


The following script uses jQuery and Modernizr to check if the input type date is not supported, if they are not it enables jQueryUI date pickers on all input[type=date] elements on the page. You could replace the insides of the if statement to whatever library or alternative you want.
$().ready(function () {
  if (!Modernizr.inputtypes.date) {
    $.datepicker.setDefaults({
      dateFormat: "dd/m/yy"
    });
    $('input[type=date]').datepicker();
  }
});

Libraries

Modernizr
jQuery
jQueryUI