Coding

HTML5 Backwards Compatible Datepicker

January 22, 2017

If you are building a form with a date element and are in need of a good datepicker that can be used across all browsers that gives the best experience to the newer browsers (html5) and also falls back to non html5 inputs using javascript and also falls back to a text box with date validation (c# mvc).

First you need to put your input on your page:

By default HTML5 will give you a datepicker on a HTML5 browser that supports the date input element, to see what broswers support this goto this link: http://caniuse.com/#search=date

As you can see from the link above, not all browsers support this though and you need a fallback, this would be jQuery ui datepicker.

Head over to https://jqueryui.com/datepicker/ and download the scripts you need (they are also in the .zip at the bottom of this post). When downloading jQuery ui you can specify what components you want and you can choose just the datepicker if this is all you need it for.

From the .zip file all you need is: jquery-ui.min.js and jquery-ui.min.css.

You will also need jQuery which you can get from https://jquery.com/download/

In your html include the scripts:

This will give you this datepicker on a non supported browser:

This will cause a problem for HTML5 browsers as both datepickers will appear, to solve this you need to include Modernizr, this can be downloaded via https://modernizr.com/ again you can choose to include what components you need, for this you need “Input Form Types”

Include the script in your html just before your inline scripts.

Then you need to change your date picker lookup to be:

This basically uses modernizr to check if your browser supports the html5 date element, otherwise it will load the jQuery script.

Overall your markup should look like this:

This will all fall back to a simple text box if either html5 isn’t supported and javascript isn’t supported, for an extra level you can add in some date validation for example in C# MVC you can use this data attribute to validate if the string entered is a valid date:

The html and files can be downloaded here HTML5Datepicker

You Might Also Like

No Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.