How to submit a form when the return key is pressed?

前端 未结 15 1079
既然无缘
既然无缘 2020-11-28 04:25

Can someone please tell me how to submit an HTML form when the return key is pressed and if there are no buttons in the form? The submit button is not there

15条回答
  •  天涯浪人
    2020-11-28 04:52

    I tried various javascript/jQuery-based strategies, but I kept having issues. The latest issue to arise involved accidental submission when the user uses the enter key to select from the browser's built-in auto-complete list. I finally switched to this strategy, which seems to work on all the browsers my company supports:

    .hidden-submit {
        border: 0 none;
        height: 0;
        width: 0;
        padding: 0;
        margin: 0;
        overflow: hidden;
    }
    

    This is similar to the currently-accepted answer by Chris Marasti-Georg, but by avoiding display: none, it appears to work correctly on all browsers.

    Update

    I edited the code above to include a negative tabindex so it doesn't capture the tab key. While this technically won't validate in HTML 4, the HTML5 spec includes language to make it work the way most browsers were already implementing it anyway.

提交回复
热议问题