-1

I saw a strange behaviour while developing HTML form. This one I didn't notice previously. So I am curious.

Suppose following is form element.

<form>
    <h2>Test</h2>
    <input type="text" name="a">
    <input type="text" name="a">
    <input type="text" name="c">
    <input type="submit" name='submit' value="Submit">
</form>

When input name='a' is focused and I press enter, the form is getting submitted by default.

I always thought form get's submitted when enter is pressed in last input element, i.e., in this case name='c'.

Now, how to make form get submitted only when enter is pressed on last input element?

Pavan Kumar
  • 1,715
  • 1
  • 24
  • 48
  • Possible duplicate of [Prevent users from submitting a form by hitting Enter](https://stackoverflow.com/questions/895171/prevent-users-from-submitting-a-form-by-hitting-enter) – Federico klez Culloca Jan 15 '18 at 16:02

1 Answers1

3

I always thought form get's submitted when enter is pressed in last input element

No.

A form will be submitted when Enter is pressed on any input.


Now, how to make form get submitted only when enter is pressed on last input element?

This is not normal behaviour. It goes against user expectations. I recommend against doing this.

  • Bind a keypress event handler to each input except the last one
  • Check if the key is Enter
  • Call preventDefault() on the event object if it is
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335