07-25-2009, 03:18 AM
var key = event.keyCode;
var keyStr = String.fromCharCode(key);
var keyNum = parseInt(keyStr);
event.keyCode = '';
thanks in advance to anyone that can help.
07-25-2009, 04:40 AM
if( isNaN(keyNum) && keyStr != "." )
But here's a question for you: How do you prevent somebody from using their mouse to copy/paste completely invalid trash in there???
You can probably tell that I'm not a fan of these filter-on-keystroke systems.
Oh, and by the VERY VERY BIG by, that code will work *ONLY* in Microsoft Internet Explorer. If you want something similar to work in all other browsers, you'll need a different set of code.
07-25-2009, 04:45 AM
That "great bit of code" has me stumped there a little; I honestly don't see how it's working at all, except maybe in just the right browser you happen to be using yourself.
Apart from the fact that you don't have that global event object in every browser, even if you did, many browsers won't just let you set that keyCode property.
If you're really happy with that piece of code, just replace that condition
if(isNaN(keyNum) && keyStr != '.')
If you happen to care about browser compatibility though, use something like that great bit of code:
el.value = el.value.replace(/[^\d\.]/g, '');
and call it like this:
(supposing you are using inline event handlers)
07-25-2009, 05:09 AM
HEH! Much better solution, Venegal.
Yeah, the code *does* work in MSIE, ugly as it is.
Of course, even your code doesn't handle the copy-paste-via-mouse-only.
But there's an easy fix for that:
<input name="price" onkeyup="CheckPrice(this)" onchange="CheckPrice(this)">
Now a copy/paste value will *also* get invalid characters zapped.
07-25-2009, 05:20 AM
I'm inclined to argue that number input fields are typically rather short and seldom copypasted into, and even if they were, nobody in their right minds would do it with their mouse, except it were a malicious attempt to circumvent validation, in which case there are other ways, and server side validation would have to catch it anyways.
But it's such an easy fix it would be quite silly to argue and not to just do it your way.