Disable input ENTER key in Chrome, FireFox, IE (including IE8), etc. by Javascript & JQuery

In order to disable the ENTER key in your textbox type input, you have to add the ‘onkeydown’ attribute and call a javascript function that checks the key and avoid to submit the form when you press ENTER key.
Input example

<input name="myName" type="text" value="Search" onclick="eraseInitialText(this);" onkeydown="disableEnter();">

Javascript function

function disableEnter() {
    var key = event.which || event.keyCode;
    if (key == 13) {
        event.cancelBubble = true;
        event.returnValue = false;
    }
}

Moreover, you can prevent all the ENTERs in your page executing a function like this in your page using JQuery and the Javascript function explained before. In my case, I allow ENTERs in inputs with the css class “accept-enter”.

function RemoveEnters() {
    $("input[type=text]").each(function () {
        if (!$(this).hasClass('accept-enter')) {
            $(this).attr('onkeydown', 'disableEnter();');
        }
    });
    $("input[type=password]").each(function () {
        if (!$(this).hasClass('accept-enter')) {
            $(this).attr('onkeydown', 'disableEnter();');
        }
    });
}

Categories:

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *