9

Along with HTML5 came a new set of input types. One of these is date and in Chrome this input produces a nice native date picker like the one shown below.

Datepicker

It also provides native date pickers on mobile devices which is my main strong point for using the new input type.

However, on Firefox (23.0.1) and IE (10), a native date picker doesn't appear and the input is treated as a normal text input. It's in these cases I want to fall back to a Javascript date picker.

The site this is for runs AngularJS and the current datepicker plugin is bootstrap-datepicker. What's the easiest way for me to disable this plugin if the browser supports native date pickers? Do I just need to check if the browser supports the date input type and disable the plugin if that's the case?

John Dorean
  • 3,744
  • 9
  • 51
  • 82
  • 2
    possible duplicate of [How to make supported on all browsers? Any alternatives?](http://stackoverflow.com/questions/18020950/how-to-make-input-type-date-supported-on-all-browsers-any-alternatives) – qwertynl Feb 05 '14 at 15:13

2 Answers2

11

You can do an HTML5 feature check like so:

// Determine if this browser supports the date input type.
var dateSupported = (function() {
    var el = document.createElement('input'),
        invalidVal = 'foo'; // Any value that is not a date
    el.setAttribute('type','date');
    el.setAttribute('value', invalidVal);
    // A supported browser will modify this if it is a true date field
    return el.value !== invalidVal;
}());

Then only initialize the bootstrap datepicker if !dateSupported.

Scottux
  • 1,577
  • 1
  • 11
  • 22
  • That's awesome. How can I remove this created element thought? I say at the end `var isSupported = el.value !== invalidVal; document.removeChild(el); return isSupported;`. So cahcing the result and try to remove, but this results in `NotFoundError: Node was not found`. I want to remove it because it's not needed any more, plus bootstrap's datepicker pops up the picker aligned to this phantom element instead of the real one. – Csaba Toth Dec 25 '14 at 07:40
  • Ok, now I'm saying a `delete el;`, so the picker doesn't popup for the phantom element. – Csaba Toth Dec 25 '14 at 08:03
  • 1
    Good thought but this answer will explain why that is unnecessary. http://stackoverflow.com/questions/1847220/javascript-document-createelement-delete-domelement – Scottux Dec 26 '14 at 14:08
1

I did the feature check like this. It includes the check if the picker is needed at all.

if (
  $('input[type="date"]').length
  && $('input[type="date"]').get(0).type == "date") {

  // Load Fallback Date Picker
}
netAction
  • 1,827
  • 1
  • 18
  • 18