Forum Moderators: open

Message Too Old, No Replies

onKeyPress Again

just detect numbers

         

humpg

5:44 pm on May 15, 2006 (gmt 0)

10+ Year Member



What I am trying to do is just allow users to only enter numbers into a text. The following code works fine in IE but not in firefox it still allows the user to enter other letters. Here is my code:

function onlyDigits(e) {
if (!e) var e = window.event;
if(e.keyCode) {
if (e.keyCode < 48 ¦¦ e.keyCode > 57)
e.returnValue = false;
} else if (e.which) {
if (e.which < 48 ¦¦ e.which > 57)
e.returnValue = false;
}
}

HTML:

<input type="text" id="answerBox" size="2" maxlength="2" align="absmiddle" onKeyPress="onlyDigits(event)">

I don't receive any errors in the firefox javascript console either? and ideas?

G

coopster

1:16 am on May 16, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



It's probably that returnValue property as I believe it is specific to IE. This should be more cross-browser compatible for you ...
function numOnly(evt) { 
evt = (evt)? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
// Allow backspace, digits, arrow keys, home, end, delete
if (charCode!= 8 && charCode > 31 && (charCode < 48 ¦¦ charCode > 57) &&
!(charCode >= 35 && charCode <= 40 ¦¦ charCode == 46)) {
window.status = "This field accepts numbers only."
return false
}
window.status = ""
return true
}

HTML:

<input type="text" id="answerBox" size="2" maxlength="2" align="absmiddle" onkeypress="return numOnly(event)">

It will set the event variable based on the browser and then monitor the key pressed changing the message in the status bar if the User Agent allows as such.

humpg

6:33 pm on May 16, 2006 (gmt 0)

10+ Year Member



Thanks coop,

That helped alot, I never even considered that the user wouldn't be able to use those keys to edit the textbox.

G

coopster

11:41 pm on May 16, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Neither did I, until they let me know about it ;)

Don't forget to rekey those pipe symbols if you copy and paste as the forum breaks the pipe symbol