Why does a FORM with one text INPUT submit on ente

2019-01-09 03:40发布

问题:

This question already has an answer here:

  • Why does forms with single input field submit upon pressing enter key in input 13 answers

I have just found out that a FORM containing only one INPUT (not hidden) will automatically submit when pressing Enter.

But a form containing at least two INPUTS (not hidden) will NOT submit when pressing enter.

(None of the scripts have a submit/button/input[type=submit] inside)

Take a look at this jsfidle. Is there an explanation/standard for this behavior?

<form id="form1" method="POST">
    <p>Does submit:</p>
    <input type="text" placeholder="focus and press enter"/>
</form>

<form id="form2" method="POST">
    <p>Does <strong>not</strong> submit:</p>
    <input type="text" placeholder="does not submit"/>
    <input type="text" placeholder=""/>
</form>

回答1:

This behaviour was introduced in the HTML 2.0 specification. See the following article for more details:

Form submission and the ENTER key?

When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form

Source: W3C Specs



回答2:

That's a browser specific implementation . . . some versions of IE actually does not do that by default, but Firefox and some of the other browsers saw fit to make the assumption that, for a form with one text box, the user (or page designer) will always want the form to submit on Enter from that field.

There have actually been multiple times that I have had to code around that . . . it's one of the more questionable browser design decisions in my opinion.

Edit:

There are more nuanced answers to your question, if you are interested . . . apparently different browsers (and their different versions) have different behaviors around this specific situation, including whether or not they submit at all, whether or not the click event occurs, etc. I can provide links to more information if you would like to read more.

But the short answer is that, it actually is intentional, if not consistently supported across browsers.



回答3:

Add the following should work in IE.

$(document).ready(function() { 
    $('input,select').keypress(function(event) { return event.keyCode != 13; }); 
  });