Falling Back to jQuery Datepicker When the Browser Doesn't Support type="date"
I've been trying to embrace the new HTML 5 input types. The one I really love is the date input type. It forces the user to select a valid date and when it posts to the server it's already in the yyyy-mm-dd format so I don't have to do any backend processing to get it into the database.
The downside to this is that it doesn't work in most browsers but it turns out we can easily create a fallback for this using the jQuery UI's Datepicker control. The code below tests to see if the browser supports the date input type and if it doesn't it creates a shadow element that acts like the data input type.
var check = document.createElement("input");
check.setAttribute("type", "date");
if(check.type === "text"){
$('input[type="date"]').each(function(){
var input = $(this);
var newInputId = input.prop('id') + 'Shadow';
input.before('<input id="' + newInputId + '">');
var newInput = $('#' + newInputId);
newInput.datepicker({
altField:'#'+input.prop('id'),
altFormat: 'yy-mm-dd'
});
var split = input.val().split('-');
newInput.val(split[1] + '/' + split[2] + '/' + split[0]);
input.hide();
});
}
Scott Keck-Warren
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.
Top Posts
- Working With Soft Deletes in Laravel (By Example)
- Fixing CMake was unable to find a build program corresponding to "Unix Makefiles"
- Upgrading to Laravel 8.x
- Get The Count of the Number of Users in an AD Group
- Multiple Vagrant VMs in One Vagrantfile
- Fixing the "this is larger than GitHub's recommended maximum file size of 50.00 MB" error
- Changing the Directory Vagrant Stores the VMs In
- Accepting Android SDK Licenses From The OSX Command Line
- Fixing the 'Target class [config] does not exist' Error
- Using Rectangle to Manage MacOS Windows