tags:

views:

391

answers:

3

I am trying to prevent users from typing certain characters in text boxes and this is the code that I have so far :

$().ready(function(){ 

        $(".textbox").keypress(function(event)
        {
        var keyVal = event.keyCode;

                    if((keyVal > 48 && keyVal < 57))// Numbers
                    {
                    return false;
                    }
         });
});

It is entering the event and the condition but the character is still inserted. Any ideas on how I go about this?

A: 

When I've had to do things like this, I've used the event onkeyup.

Instead of stripping out the chars automatically (which may lead to user confusion), why not have a regex that checks for valid chars on key up, and then maybe displays a side note to the input, something like 'You may not enter numbers in this field', or something more specific to the actual input field, 'Your city name may not include number(s).'.

alex
Still have the same issue, and as I recall the character is inserted on key down, since if you keep the button pressed the characters are repeated in the textbox.
Drahcir
A: 

your code seems okay but please study jquery.numeric by Sam Collett. He is doing the stuff successfully!

TheVillageIdiot
+1  A: 

Your keyVal assignment didn't take all browsers into account. This piece of code works in Firefox, IE7, Safari, Chrome and won't let you type numbers in the field, tested with a normal text input element:

$().ready(function(){
  $(".textbox").keypress(function(event){
    var keyVal = (event.charCode ? event.charCode : ((event.keyCode) ? event.keyCode : event.which));
      if((keyVal > 48 && keyVal < 57))// Numbers
      {
         return false;
      }
    });
});
CtlAltDel