How to stop element with first onclick event to be fired when enter key is pressed first time

后端 未结 2 1991
情深已故
情深已故 2021-01-16 06:17

I was fixing a bug in a jsp page in which even though a function is defined with onkeypress event to click a particular button (actually its an image of button

2条回答
  •  甜味超标
    2021-01-16 06:45

    The following will probably work. By preventing the default action of the keypress it should stop the browser from triggering the standard "form submit" — which is what I think is happening.

    function handleEnter(e)
    {
      e || (e = window.event); /// support for both ie and non-ie browsers
      if(e.keyCode==13)
      {
        alert('nothing');
        // old ie support
        e.cancelBubble = true;
        e.returnValue = false;
        // non-ie
        e.preventDefault && e.preventDefault();
        e.stopPropagation && e.stopPropagation();
      }
    }
    

    You have to bear in mind though that if you are preventing default for enter on the whole page, it will stop it working for textareas and other places where enter might be used. If this is a problem you could decide whether or not to prevent the default action depending on:

    var elm = e.srcElement || e.target;
    

    elm should contain the triggering element of the event. scrElement is for old IE and target is for non-IE browsers. For example, you could use this to shortcircuit your code before reaching the prevent default.

    if ( elm.nodeName == 'textarea' ) return;
    

    I don't have IE8 lying around to test this however, but considering the following link, it is likely to work:

    http://support.microsoft.com/kb/298498

提交回复
热议问题