Keydown Event to override return key not working in Firefox

I have the following simple javascript code that processes the return key, I don’t want to submit the form when the return key is pressed in the text box.

All this works fine, but in Firefox, if I show a warning message, it stops working and the form starts receiving, while the exact code without a warning message works fine and stops sending the form. I don’t understand why the notification spoils the party.

    $("document").ready(function () {
        $("#input1").keydown(OnKeyDown);
    });


    function OnKeyDown(e) {
        if (e.keyCode == 13) {

            // alert('this will fail');  // Adding alert makes the form submit

            stopBubble(e);
            return false;
        }
    }

    function stopBubble (e) {

        // If an event object is provided, then this is a non-IE browser
        if (e && e.stopPropagation)
        // and therefore it supports the W3C stopPropagation() method
            e.stopPropagation();
        else
        // Otherwise, we need to use the Internet Explorer
        // way of cancelling event bubbling
            window.event.cancelBubble = true;
    }


  <input type="text" id="input1" value="">
+3
source share
3 answers

I do not know whether it is normalized or not. But that’s how I should do it so that it works in all browsers:

$(whatever).keypress(function (e) {

    var k = e.keyCode || e.which;
    if (k == 13) {
        return false; // !!!
    }
});
+4
source

jQuery , :

$(document).ready(function () {
    $("#input1").keydown(OnKeyDown);
});

function OnKeyDown(e) {
    if (e.which == 13) {        //e.which is also normalized
        alert('this will fail');
        return false;
    }
}

return false , jQuery event.preventDefault() event.stopPropgation() . :

$(function () {
  $("#input1").keydown(function() {
    if (e.which == 13) return false;
  });
});
+2
        textBox.onkeydown = function (e) {
            e = e || window.event;
            if (e.keyCode == 13) {
                if (typeof (e.preventDefault) == 'function') e.preventDefault();
                if (typeof (e.stopPropagation) == 'function') e.stopPropagation();
                if (typeof (e.stopImmediatePropagation) == 'function') e.stopImmediatePropagation();
                e.cancelBubble = true;
                return false;
            }
        }
0
source

Source: https://habr.com/ru/post/1767973/


All Articles