views:

53

answers:

3

I'm trying to limit what our users will be able to type in inputs, using javascript/jquery.

Problem is, I have to limit this to Uppercase chars only, and numbers.

Here's what I coded previously :

$(input).keypress(function(e){
                    if ($(input).attr("class")=="populationReference"){
                        var ValidPattern = /^[A-Z_0-9]*$/;
                        var char = String.fromCharCode(e.charCode);
                        if (!ValidPattern.test(char) && e.charCode!=0){
                            return false;
                            e.preventDefault();
                        }
                    }
                });

If Firefox supports charCode, IE doesn't. How then, could I test if the user is typing uppercase or lowercase characters ? Thanks for any help !

+1  A: 
Andy E
+1  A: 

use e.which instead of e.charCode aswell.

Kind Regards

--Andy

jAndy
+1  A: 

From the jquery manual for keypress():

To determine which character was entered, we can examine the event object that is passed to the handler function. While browsers use differing attributes to store this information, jQuery normalizes the .which attribute so we can reliably use it to retrieve the character code.

In other words, if you are using jquery, you are safe to use e.which to return the character code, so in your case:

var char = String.fromCharCode(e.which);

is the change to make.

But personally, I would avoid punishing users for lower-case input by converting it for them. Maybe add this modification:

$("input.populationReference").keypress(function(e){
                        var ValidPattern = /^[A-Z_a-z_0-9]*$/;
                        var char = String.fromCharCode(e.charCode);
                        if (!ValidPattern.test(char) && e.charCode!=0){
                            return false;
                            e.preventDefault();
                        } else {
                          var inputval = $(this).value(); 
                          $(this).value(inputval.toUpperCase());
                        }
                });
Anthony
this made it. One more question : what about TAB and ARROW keys ? with the above code, none of them works. Is there a way to special treat them ?
pixelboy