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

后端 未结 2 1973
情深已故
情深已故 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:47

    I know this is an old question, but I did not find any other questions/answers for this, and I was having this same issue with buttons.

    But for some reason when I look at the "event" that is passed into javascript function, there is no keyCode passed in with it, so I can not distinguish which key was pressed. FYI "event" was only passing in isTrusted property (and nothing else), but that is another question for another time...

    My solution was that I just added a button with onclick="return false;" and style="display:none;" in front of all the other elements so that the ENTER key affects this element and is essentially ignored, and is invisible. With onclick='return false;' the form will NOT be submitted. With onclick='return true;' the form WILL be submitted.

    SECOND ANSWER So this is maybe for a slightly different issue that only involves BUTTONS (not INPUTS), but this may be good to know for some people (like me) that did not know this... When you have a button in a form, it defaults to type "submit" which means the first button in a form will have its onclick event triggered by the ENTER key. To prevent this from happening, simply assigm type="button" to the button, and enter key will no longer affect it.

提交回复
热议问题