简体   繁体   中英

event.returnvalue=false is not working in firefox?

I am working on an old application to make it compatible with firefox. As the old application does not uses Jquery I have to do all my stuffs using Javascript only.

I have a input field for entering date.This field should only allow 0-9 numeric values. So I have modified the code like this for making it compatible with firefox.

var event = window.event || ffEvent ; //ffEvent is the function argument
var intKeyCode = event.keyCode || event.which;
if (intKeyCode < 48 || intKeyCode > 57){
 if(event.preventDefault){
   event.preventDefault();
 }
 else{
   event.returnValue = false;
 }
}

But now the problem is event.returnValue = false allows keys like Backspace,Tab,Delete,Arrow buttons where as event.preventDefault() does not allow these buttons. One must allow these buttons for a input field.

So is there any solutions for firefox which exactly behave same as event.returnValue=false

why not use the keyCodes to check if the character is digit or not

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    var event = window.event || ffEvent ; //ffEvent is the function argument
    var intKeyCode = event.keyCode || event.which;
    if (intKeyCode > 31 && (intKeyCode < 48 || intKeyCode > 57))
         return false;

    return true;
}

in the keypress of input field call this event, as

onkeypress="return isNumberKey(event)

All you need to do is skip the event.preventDefault() when the key is one of the keys you want to allow:

 window.onload = function () { document.getElementById('myField').onkeypress = function (event) { var keyCode = event.keyCode || event.which, allowedKey = keyCode === 8 || // backspace keyCode === 9 || // tab keyCode === 13 || // enter keyCode === 37 || // left keyCode === 39 || // right keyCode === 46 || // del (keyCode >= 48 && keyCode <= 57); if (!allowedKey) { event.preventDefault(); } }; }; 
 <input type="text" id="myField" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM