A far superior method for detecting supported input types is to simply create an input element and loop through all of the different input types available and check if the type
change sticks:
var supported = { date: false, number: false, time: false, month: false, week: false },
tester = document.createElement('input');
for (var i in supported){
try {
tester.type = i;
if (tester.type === i){
supported[i] = true;
}
} catch (e) {
// IE raises an exception if you try to set the type to
// an invalid value, so we just swallow the error
}
}
This actually makes use of the fact that browsers which do not support that particular input type will fall back to using text, thereby allowing you to test if they're supported or not.
You can then use supported['week']
, for instance, to check for the availability of the week
input type, and do your fallbacks through this. See a simple demo of this here: http://www.jsfiddle.net/yijiang/r5Wsa/2/. You might also consider using Modernizr for more robust HTML5 feature detection.
And finally, a better way to get outerHTML
is to, believe it or not, use outerHTML
. Instead of
var inputAttr = $('<div>').append($(this).clone()).remove().html().toLowerCase();
Why not just use:
var inputAttr = this.outerHTML || new XMLSerializer().serializeToString(this);
(Yes, as you can see, there is a caveat - outerHTML
isn't supported by Firefox, so we're going to need a simple workaround, from this Stack Overflow question).
Edit: Found a method to do testing for native form UI support, from this page: http://miketaylr.com/code/html5-forms-ui-support.html. Browsers that support the UI for these types in some way should also prevent invalid values from been entered into these fields, so the logical extension to the test we're doing above would be this:
var supported = {date: false, number: false, time: false, month: false, week: false},
tester = document.createElement('input');
for(var i in supported){
tester.type = i;
tester.value = ':(';
if(tester.type === i && tester.value === ''){
supported[i] = true;
}
}
Again, not 100% reliable - this is only good for types that have certain restrictions on their values, and definitely not very good, but it's a step in the right direction, and certainly would solve your problem now.
See the updated demo here: http://www.jsfiddle.net/yijiang/r5Wsa/3/