allow only numbers in an input

P

PJ

I've been using this function to limit a text input to numbers only with success on an old site.

function checkForInt(evt) {
var charCode = ( evt.which ) ? evt.which : event.keyCode;
return ( charCode >= 48 && charCode <= 57 );
}<input id="txt" type="text" onkeypress="return checkForInt(event)" />However, on a new site I am building, the text input not only disallows letters, it also doesn't allow tabbing to the next control, hitting return, backspace, delete, left/right arrow, etc. I obvioulsy want to allow these keys. The only difference between the two is that the new site is xhtml 1.0 transitional. Has anyone else experienced this?

Also, what is the proper syntax to wire up an event like this without typing the event attribute in the markup itself?

document.getElementById('txt').onkeypress = function(event) { return checkForInt(event); }

????
Thanks,~PJ
 
P

PJ

I need a filter on both sites. I have modified the function to the
following now and it seems to work.

function checkForInt(evt) {
//notice that the check is != null now, as the tab key has a value of 0
var charCode = ( evt.which != null ) ? evt.which : event.keyCode
//charCodes < 32 include tab, delete, arrow keys, etc
return (charCode < 32 || (charCode >= 48 && charCode <= 57))
}

However:
document.getElementById("txt").onkeypress = checkForInt;
does not work in Firefox as an argument needs to be passed in order to pass
the event. How do you assign an event in code and pass arguments to it?

Thanks
~PJ
 
P

PJ

Ok, the reason it wasn't working for me is I had accidently left the
attribute for the event on while testing. That last function I used was no
good in IE as it throws an error that evt.which is null or not an object, as
evt itself is null in IE. The latest iteration I have is:

function checkForInt(evt) {
evt = ( evt ) ? evt : window.event;
var charCode = ( evt.which ) ? evt.which : evt.keyCode
return (charCode <= 31 || (charCode >= 48 && charCode <= 57))
}

Come to think of it, it should be titled "checkForPosInt", but oh well...

As for wiring events, I like to take the seperation a bit further and use
Ben Nolan's Behaviour file. I've found this rather nifty way that uses css
selectors. http://bennolan.com/behaviour/

var gameRules = {
'#txt' : function(element) {
element.onkeypress = checkForInt;
} ,
Behaviour.register(gameRules);

Thanks again Ian
~PJ
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top