Submitting a form by pressing enter without a submit button

前端 未结 20 1575
你的背包
你的背包 2020-11-22 06:46

Well I am trying to submit a form by pressing enter but not displaying a submit button. I don\'t want to get into JavaScript if possible since I want everything to work on a

相关标签:
20条回答
  • 2020-11-22 06:55

    I think you should go the Javascript route, or at least I would:

    <script type="text/javascript">
    // Using jQuery.
    
    $(function() {
        $('form').each(function() {
            $(this).find('input').keypress(function(e) {
                // Enter pressed?
                if(e.which == 10 || e.which == 13) {
                    this.form.submit();
                }
            });
    
            $(this).find('input[type=submit]').hide();
        });
    });
    </script>
    
    
    <form name="loginBox" target="#here" method="post">
        <input name="username" type="text" /><br />
        <input name="password" type="password" />
        <input type="submit" />
    </form>
    
    0 讨论(0)
  • 2020-11-22 06:56

    HTML5 solution

    <input type="submit" hidden />
    
    0 讨论(0)
  • 2020-11-22 06:57

    IE doesn't allow pressing the ENTER key for form submission if the submit button is not visible, and the form has more than one field. Give it what it wants by providing a 1x1 pixel transparent image as a submit button. Of course it will take up a pixel of the layout, but look what you have to do to hide it.

    <input type="image" src="img/1x1trans.gif"/>
    
    0 讨论(0)
  • 2020-11-22 06:59

    Instead of the hack you currently use to hide the button, it would be much simpler to set visibility: collapse; in the style attribute. However, I would still recommend using a bit of simple Javascript to submit the form. As far as I understand, support for such things is ubiquitous nowadays.

    0 讨论(0)
  • 2020-11-22 07:01

    Another solution without the submit button:

    HTML

    <form>
      <input class="submit_on_enter" type="text" name="q" placeholder="Search...">
    </form>
    

    jQuery

    $(document).ready(function() {
    
      $('.submit_on_enter').keydown(function(event) {
        // enter has keyCode = 13, change it if you want to use another button
        if (event.keyCode == 13) {
          this.form.submit();
          return false;
        }
      });
    
    });
    
    0 讨论(0)
  • 2020-11-22 07:01

    the simplest way

    <input type="submit" style="width:0px; height:0px; opacity:0;"/>
    
    0 讨论(0)
提交回复
热议问题