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

前端 未结 15 979
既然无缘
既然无缘 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 05:07

    Use the <button> tag. From the W3C standard:

    Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.

    Basically there is another tag, <button>, which requires no javascript, that also can submit a form. It can be styled much in the way of a <div> tag (including <img /> inside the button tag). The buttons from the <input /> tag are not nearly as flexible.

    <button type="submit">
        <img src="my-icon.png" />
        Clicking will submit the form
    </button>
    

    There are three types to set on the <button>; they map to the <input> button types.

    <button type="submit">Will submit the form</button>
    <button type="reset">Will reset the form</button>
    <button type="button">Will do nothing; add javascript onclick hooks</button>
    

    Standards

    • W3C wiki about <button>
    • HTML5 <button>
    • HTML4 <button>

    I use <button> tags with css-sprites and a bit of css styling to get colorful and functional form buttons. Note that it's possible to write css for, for example, <a class="button"> links share to styling with the <button> element.

    0 讨论(0)
  • 2020-11-28 05:07

    Since display: none buttons and inputs won't work in Safari and IE, I found that the easiest way, requiring no extra javascript hacks, is to simply add an absolutely positioned <button /> to the form and place it far off screen.

    <form action="" method="get">
      <input type="text" name="name" />
      <input type="password" name="password" />
      <div class="yourCustomDiv"/>
      <button style="position:absolute;left:-10000px;right:9990px"/>
    </form>
    

    This works in the current version of all major browsers as of September 2016.

    Obviously its reccomended (and more semantically correct) to just style the <button/> as desired.

    0 讨论(0)
  • 2020-11-28 05:09

    Here is how I do it with jQuery

    j(".textBoxClass").keypress(function(e)
    {
        // if the key pressed is the enter key
        if (e.which == 13)
        {
            // do work
        }
    });
    

    Other javascript wouldnt be too different. the catch is checking for keypress argument of "13", which is the enter key

    0 讨论(0)
提交回复
热议问题