Tip: Prevent non-integer input

Monday, March 31, 2008 at 9:15 AM



Certain gadgets, such as calculators or leap year finders, should restrict user input to integer values. To detect when the user starts entering non-integer data into an element such as an edit area, you can use an onkeypress handler:
function onKeyPress() {
var a = editbox.value;

if (a*1 == a) {
// continue the action
} else {
// show an error message
}
}
Have a tip you'd like to share? Send it to gd-developer AT google DOT com. To see all tips, choose the Tips label.

1 comment:

recover said...

That's a very clever way of solving it. I don't know if this does any difference, but wouldn't it be proper to use the strict equal operator (===)?
See http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Operators:Comparison_Operators