Search code examples
javascriptregexfirefoxtextinputkeycode

js disabling backspace functionality in firefox


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.


Solution

  • 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