Introduction

In this post I'll show a simple way of handling date inputs that will work across modern and not so modern browsers. You'll also learn how to implement a mobile-friendly date picker in jQuery Mobile.

You can download the source codes from this GitHub repo.

Good ol' date picker

The standard approach for giving the users a way to choose a date used to be:

  1. Add an ordinary text input to your HTML
    <input type="text" id="date-picker-here" />
  2. Enhance it with JavaScript (my personal favourite is jQuery UI Date Picker)
    $(function() {
      $("#date-picker-here").datepicker();
    });

As a result you would get a date picker that looks like this:

HTML5 date input

With the introduction of HTML5, we got a new input type, the date input:

<input type="date" />

It's as simple as that. The way the native date picker looks depends on the browser implementation. In Chrome it looks something like that:

The only problem with the native date input is that it's not supported in all browsers and platforms. Currently, you are forced to provide a fallback of some sort.

Modernizr to the rescue

To detect, if user's browser supports date inputs Modernizr seems like the best choice. The availability of date inputs can be checked by testing the flag:

Modernizr.inputtypes.date

The whole code could look like this:

var nativeDateInputIsSupported = Modernizr.inputtypes.date;
if (!nativeDateInputIsSupported) {
  $("input[type='date']").datepicker();            
}

What about mobile?

How about mobile devices? Unfortunately, the standard jQuery Date Picker is not very mobile-friendly. If you're using jQuery Mobile you may find Mobi Pick the simplest and easiest to configure.

The code behind is similar to that of jQuery UI:

$(document).on("pagecreate", function() {
  $("#date-picker-here").mobipick();
});

And here is the result:

Mobile with fallback

The Mobi Pick date picker looks nice, however users probably expect a behavior similar to that of the platform they're using. This can be accomplished with the native date inputs. Again, we should provide a fallback. Let's use Mobi Pick for this:

$(document).on("pagecreate", function() {
  var nativeDateInputIsSupported = Modernizr.inputtypes.date;
  if (!nativeDateInputIsSupported) {
    $("input[type='date']").mobipick();            
  }
});

The End

I hope you enjoyed this post. Please, check this GitHub repo, if you would like to download the examples.