You’d think that after all this time the latest versions of the major browsers would all pretty much be the same. Uh, not really. Especially when it comes to HTML5 implementation. HTML5 is pretty new but jeez, since it’s so new don’t you think that browsers that implement features would at least do it the same? Right now I’m talking about <input type=”number” />. It’s supported in IE and Chrome, not Firefox yet. I hear the next version of Firefox will support it.
A web app that I’m working on has a them because I want to enter a bunch of numbers. Since Firefox doesn’t support it, it doesn’t matter. You can enter anything. In Chrome, you can enter any text you want but if it’s not strictly a number, then the ‘value’ property of the dom object is blank. This causes problems because there is still a value on the screen so if you try and notify that there is no value the user’s going to think you suck. IE actually has the right implementation according to the spec. If you enter a value that’s not a number, the field goes blank when it loses focus. Now the value property of the dom object matches what shows on the screen.
Obviously I can look at the ‘validity’ property of the dom object but even that is inconsistent across browsers and I really don’t want to check a bunch of different places to know if the input is correct. Fortunately, I can make my life quite a bit easier with just a few lines of code. And jQuery.
$("input[type=number]").on('blur', function() { if (this.validity && this.validity.badInput) { this.value = null; } });
It should be pretty obvious what’s going on here but I’ll explain any way. Chrome’s implementation of the ValidityState object has that badInput property and wouldn’t you know, its value is ‘true’ when the input is bad. What I’ve done here is mimic IE’s behavior for chrome. Imagine that. We’re usually trying to get IE to mimic the other browsers’ behavior.
Firefox 28 is supposed to have support for number input types. It’ll probably be different than Chrome and IE so I’ll probably have to adjust this script. For now, it’s great.