How can I disable the ESC key function in JavaScript?

My chat app has text boxes that get the user's login details.

when filling in user details. If the user suddenly pressed the ESC key, the data will be lost.

Do I need to disable the ESC key function? what event should i use? How can i do this.

my Java Script code,

function esc(e){
    e = e || window.event || {};
    var charCode = e.charCode || e.keyCode || e.which;
    if(charCode == 27){
    return false;
    }
}

      

Searched a lot on Stack Overflow and google. Nothing succeeded. Please help me to do this. Thank..

+3


source to share


4 answers


I got a solution to control the keys "F5, Esc, BackSpace (BS)" with the following code.

My Java Script code will be,



document.attachEvent("onkeydown", win_onkeydown_handler);

function win_onkeydown_handler() {
    switch (event.keyCode) {

    case 116 : // 'F5'
         event.returnValue = false;
         event.keyCode = 0;
         break;  

    case 27: // 'Esc'
        event.returnValue = false;
        event.keyCode = 0;
        break;

    case 08: // 'BackSpace'
        if (event.srcElement.tagName == "INPUT"
                || event.srcElement.tagName == "TEXTAREA") {
        } else {
            event.returnValue = false;
            event.keyCode = 0;
        }
        break;

    }
}

      

Thanks to everyone who supported me to do this and for your suggestions.

+3


source


You can bind an eventlistener to your input field to catch the event when the button is clicked Escand suppress it.

document.querySelector("input").addEventListener("keydown",function(e){
    var charCode = e.charCode || e.keyCode || e.which;
    if (charCode == 27){
         alert("Escape is not allowed!");
        return false;
    }
});

      



Example

+5


source


I used this for the login popup:

jQuery(document).keyup(function(e){
    if(e.keyCode==27 && popupStatus==1){
    // alert('not allowed !!!');
        // or any other code
     return false;
    }
});

      

+2


source


I did something similar using jquery to constrain the input of numbers

    $(inputBox).keydown(function(event) {
        // Allow only backspace and delete
        var allowed_keys = [
            46, // delete
            8, // backspace
                 ];
        if ($.inArray(event.keyCode, allowed_keys) != -1) {
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (event.keyCode < 48 || event.keyCode > 57 ) {
                event.preventDefault(); 
            }   
        }
    });

      

0


source







All Articles