On a project that I was recently working on, I had a series of text input boxes that I wanted to be numeric only fields. I have my PHP form validation to check that the data is numeric before entering any information in to the database, and I always use mysql_real_escape_string() on the data I am saving. But to save loat time and page refreshed, I decided to add some extra validation with the Mootools javascript library which I am using trough out the site already.
Update to Numbers Array
I have updated the Numbers array to include the number pad on full size keyboards.
Allowing Numbers:
Because I have a bunch of inputs that I need validated, I decided that I would assign each input with a matching class, then Scan the page for that class with my Javascript, then only allow specific key codes to be entered.
<h3>Your Age...</h3> <p><label for="age">Age</label><input type="text" name="age" value="" id="age" class="numeric"/></p>
Inside of my DOM Ready state, I run this simple code.
window.addEvent('domready', function() { var numbers = [8, 48,49, 50, 51,52,53,54,55,56,96,97,98,99,100,101,102,103,104,105]; $$('.numeric').each(function(item) { item.addEvent('keydown', function(key) { for (i = 0; i < numbers.length; i++) { if(numbers[i] == key.code) { return true; } } return false; }); }); });
If you can see the line I have specified only the Key Codes that are allows, I have allowed for numeric numbers and the Delete Key.
var numbers = [8, 48,49, 50, 51,52,53,54,55,56,96,97,98,99,100,101,102,103,104,105];
Other Uses:
You could disallow any key entry, This isnt a great idea, but could be used when maybe using an overlay, or special effect.
window.addEvent('domready', function() { window.addEvent('keydown', function() { return false; }); });
Dissallowing Keys:
You could simply reverse this function, to block a small amount of keys rather than just allowing some, it would be as simple as changing the locations of your return true/false statements.
This example would allow anything except numbers.
window.addEvent('domready', function() { var numbers = [48,49, 50, 51,52,53,54,55,56,96,97,98,99,100,101,102,103,104,105]; $$('.numeric').each(function(item) { item.addEvent('keydown', function(key) { for (i = 0; i < numbers.length; i++) { if(numbers[i] == key.code) { return false; } } return true; }); }); });
Related posts:

4 Responses to “Controlling Input with Mootools Javascript”
Thomas J. Brown 23/04/2009 03:39am
Sheldon 27/04/2009 09:16am
Thomas J. Brown 29/04/2009 08:16am
I do want to point out that, in the demo, the numbers-and-delete-only doesn't let me delete (with either the delete or backspace keys). It also doesn't let me tab, which might be a useful keystroke to allow.
Otherwise, very cool!
Sheldon 01/05/2009 09:29am