Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only numbers in JavaScript [duplicate]

Tags:

javascript

Possible Duplicate:
HTML Text Input allow only Numeric input

I used this script

function isNumberKey(evt)
  {
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;                        
    if (charCode > 31 && (charCode < 47 || charCode > 57))
    return false;
    if (e.shiftKey) return false;
    return true;
 }

But this script not working in firefox alone. Any alternatives to restrict user for shift key in javascript?

like image 490
itzArun Avatar asked Jul 16 '26 11:07

itzArun


1 Answers

event is not defined in Firefox, it's breaking your code. Put it after testing for evt:

function isNumberKey(evt)
  {
    var e = evt || window.event; //window.event is safer, thanks @ThiefMaster
    var charCode = e.which || e.keyCode;                        
    if (charCode > 31 && (charCode < 47 || charCode > 57))
    return false;
    if (e.shiftKey) return false;
    return true;
 }

Fiddle

Check your error console next time. :)

like image 77
Fabrício Matté Avatar answered Jul 18 '26 23:07

Fabrício Matté



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!