js disabling backspace functionality in firefox

2019-01-20 04:46发布

I have following javascript to prevent user from entering invalid characters into a text field. It's working well in chrome but not in firefox. It's preventing the backspace key to be entered in the text field in firefox.

function onlyNumbers(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[0-9]|\./;
    if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault(); 
    }
}

Can anyone please have a look and propose a fix for firefox to not prevent backspace key to act on a text field ?

Probably I guess, adding the regex for the backspace character would do the job here. Does anyone know, how to add the regex for matching the backspace

Edit:

Also, the above code has supposed to interrupted with the Tab key behaviour, I am not able to jump to next fields in the form using Tab key.

2条回答
【Aperson】
2楼-- · 2019-01-20 05:19

see http://jsfiddle.net/8ZJZD/1/

var el=document.getElementById('cnfMobileNo');
el.onkeydown=function onlyNumbers(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    if(key===8){return;}
    key = String.fromCharCode(key);
    var regex = /[0-9]|\./;
    if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
    }
}

Just use if(key===8){return;}

Edit:

If you want to exclude more keys, use

var el=document.getElementById('cnfMobileNo');
el.onkeydown=function onlyNumbers(evt) {
    var theEvent = evt || window.event,
        key = theEvent.keyCode || theEvent.which,
        exclusions=[8,9]; /*Add exceptions here */
    if(exclusions.indexOf(key)>-1){return;}
    key = String.fromCharCode(key);
    var regex = /[0-9]|\./;
    if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
    }
}

See it here: http://jsfiddle.net/8ZJZD/2/

You can know the keyCode of each key using alert(key)

(before key = String.fromCharCode(key)).

You could also exclude

  • The arrow keys: 37,38,39,40
  • Enter: 13
  • Context menu: 93
  • Start and End: 36,35
查看更多
你好瞎i
3楼-- · 2019-01-20 05:27

Im not sure of the backspace regex but this should work too

$("#myInput").bind('keyup', function(){
     val1 = $(this).val();
     $(this).val(val1.replace(/[^0-9.]/g,''));
});

You might do away with bind and directly attach keyup

Fiddle - jsfiddle

查看更多
登录 后发表回答