1

I have a very simple piece of JavaScript that is not working 100%, and I can't figure out why.

<input type="text" onKeyPress="return numbersOnly(event);" />
function numbersOnly(event){
    // Return "true" for all numbers and the delete (a.k.a., backspace) key.
    return ((event.charCode >= 48 && event.charCode <= 57) || event.charCode == 8) ? true : false;
}

It will let me input just the numbers exactly like I want, but it won't pick up the delete (a.k.a., backspace) key.

EDIT: The weird thing is this works for me in IE 9 but not Firefox.

Brian
  • 1,726
  • 2
  • 24
  • 62

1 Answers1

2

You're facing some cross browser issues with events. Try this

function numbersOnly(event) {
    var key = (event.hasOwnProperty('charCode')) ? event.charCode : event.which;
    // Return "true" for all numbers and the delete (a.k.a., backspace) key.
    return ((key >= 48 && key <= 57) || key == 8) ? true : false;
}
chazsolo
  • 7,873
  • 1
  • 20
  • 44