HTML5 input type=”date” with javascript fallback

Standard

HTML5 brings great new features which will ease development. However, currently there is a gap between browsers that support HTML5 attributes and those who do not. As of October around 60% of desktop browsers and 80% of mobile devices are HTML5 compliant. This means developers still need support the additional 40% which fallback techniques.

HTML5 date input field

A good example is the new date input field. If your browser is HTML5 compliant it generate a date picker for you to use automatically, thus only requiring the developer to create the input field as so:

<input name="start_date" type="date" placeholder="mm/dd/yyyy" />

If the browser does not support HTML5 then no restriction on the date format will occur. This is why javascript is a beautiful tool.

Providing a fallback

Using a combination of Modernizr, jQuery, and bootstrap-datetimepicker javascript libraries a HTML5 date field can be emulated. Modernizr is a library use for feature detection. It can recognize if the HTML5 date object is available to the browser. If the date object is not available then the bootstrap-datetimepicker will bind to the input and provide a calendar for the user.

The following is the javascript which a datetime picker to the input field below if necessary.

$(document).ready(function () {
    // If they do not have HTML5 date then provide a datepicker using javascript
    if (!Modernizr.inputtypes.date) {
            
        $('#startDatetime').datetimepicker({
            pickDate: true,
            pickTime: false
        });
            
     }
});

The input field has classes attached that are from the bootstrap 3 library. These libraries add a hint of design to the end result.

<div class="input-group date" id="startDatetime">
   <input name="end_date" type="date" placeholder="mm/dd/yyyy" class="form-control"/>
   <span id="endDateIcon" class="input-group-addon">
      <span class="glyphicon glyphicon-calendar"></span>
   </span>
</div>

Note: In this example I used the bootstrap-datetimepicker library, however any javascript date picker may be substituted in its place. The following libraries were used: bootstrap3, modernizr, momentjs (required by bootstrap-datepicker), and jQuery 2.1.0.

A example of this project can be seen on JSFiddle.

Leave a Reply

Your email address will not be published.