简体   繁体   中英

keydown Event to override return key does not work in Firefox

I have the following simple javascript code, which handles the Return Key, I don't want to submit the form when the return key is pressed in the textbox.

All this works fine, but in Firefox, if i show an alert message, then it stops working and the form starts getting submitted, whereas the exact code without alert message works fine and stops the form from being submitted. I dont understand why alert is spoiling 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="">

I don't really know if the event is normalized or not. But this is how I have to do it for it to work in all browsers:

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

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

jQuery normalizes this already, you can just do:

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

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

When you do return false from a handler, jQuery calls event.preventDefault() and event.stopPropgation() internally already . You can also do the anonymous function version:

$(function () {
  $("#input1").keydown(function() {
    if (e.which == 13) return false;
  });
});
        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;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM