Question

I want to write a shim for older browsers that don't support <input type="number">.

This is easy to detect as, in those browsers, any input where you set the type to number will report the type as text. So good so far.

So what I want to do is find every <input type="number"> and hook up events for these older browsers.

The problem is: how do I find them?

  • $('input[type=number]').length === 0 (of course).
  • $('input[name=aKnownNumberField]')[0].type === 'text' again, not a surprise as this is the check used for feature detection in the first place.
  • $($('input[name=aKnownNumberField]')[0]).parent().html().indexOf('type="number"') (or any similar check of the HTML) also fails because the HTML returned will be that according to the browser's DOM.

Note that I'm using jQuery in my examples, but I'm happy for non-jQuery answers.

How do I detect <input type="number"> in browsers that don't support them?

Was it helpful?

Solution

If you're using jQuery, you can get them using .filter():

var $unsupported = $('input').filter(function() {
    return this.type !== $(this).attr('type');
});

This'll select all unsupported inputs, so you may want to filter that further using .filter('[type="number"]') or do that from within the filtering function.

A pure JS solution isn't much different:

var inputs = document.getElementsByTagName('input');

for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].type === inputs[i].getAttribute('type')) {
        continue;
    }

    // inputs[i] isn't supported by the browser
}

And a demo: http://fiddle.jshell.net/PENRD

I tested it in IETester and it worked down to IE6.

OTHER TIPS

$.expr[':'].realtype = function(objNode,intStackIndex,arrProperties,arrNodeStack)
{
  return $(objNode).attr('type')===arrProperties[3];
}

var numbers=$('input:realtype("number")');

jsfiddle: http://jsfiddle.net/kingmotley/3sMQf/2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top