Stephen Jenkins
Stephen Jenkins

Reputation: 1836

How to feature detect an input type

Can't seem to find a Modernizr-free solution on here, but how can I detect support for a specific input type, not attribute?

For instance, for an attribute:

var supportsRequired = 'required' in document.createElement('input')
if (supportsRequired) {
    // support
} else {
    // no support
}

Is there an easy way to do this with input types? One thing I don't want to do is 'swap' the input type should it not be supported. Is there something similar to this, to only test?...

var supportsEmailType = 'email' in input.type
if (supportsEmailType) {
    // support
} else {
    // no support
}

Any help appreciated.

Upvotes: 4

Views: 143

Answers (1)

Paul
Paul

Reputation: 141829

From here:

If your browser supports that particular input type, the type property will retain the value you set. If your browser doesn't support that particular input type, it will ignore the value you set and the type property will still be "text".

This will correctly detect if the 'email' type is supported and you can reuse the function to detect other types:

if (supportsInputType('email')) {
    // support
} else {
    // no support
}

function supportsInputType(type){
    var i = document.createElement('input');
    i.setAttribute('type', type);
    return i.type === type;
}

Upvotes: 2

Related Questions