Human Being
Human Being

Reputation: 8387

How to disable the function of ESC key in JavaScript?

In my chat application there are some text fields which gets the user login details.

When filling the user details, if a user suddenly pressed the ESC key, the data will be lost.

If need to disable the function of ESC key, which event I need to use? How can I do that.

My JavaScript code is:

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

I searched a lot in Stack Overflow and Google; nothing worked. Please, can anyone help me to do that?

Upvotes: 6

Views: 37282

Answers (4)

Human Being
Human Being

Reputation: 8387

I got the solution to control the " F5 , Esc , BackSpace(BS) " keys 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 who are all supported me to do this and for your suggestions.

Upvotes: 2

Riju Mahna
Riju Mahna

Reputation: 6926

I have used this for a login popup code:

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

Upvotes: 1

Christoph
Christoph

Reputation: 51211

You can bind an eventlistener to your input field to catch the Event when Esc is pressed and supress 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

Upvotes: 7

Dave Gill
Dave Gill

Reputation: 244

I have done something similar using jquery to limit entry to 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(); 
            }   
        }
    });

Upvotes: 0

Related Questions