8

I have a form with two buttons, one input[type=submit] and one plain button which is the cancel button.

I have two event handlers, one bound to the form on submit and one bound to the button on click.

When I submit the form by pressing enter in an input the click event on the button fires (and before the submit event I might add), why is this?

This happens in both gecko and webkit.

Here's a working example: http://jsfiddle.net/q3JPR/

If you submit by pressing enter I want the submit event to trigger, not the click event.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nicklas A.
  • 6,501
  • 7
  • 40
  • 65
  • This also happens to me, I've spent roughly an hour searching the whole web and have not found any documentation for this behaviour, let me know if you found something. – asumaran Oct 14 '13 at 07:32

2 Answers2

6

If you change your button to be <input type="button"... then your events will behave properly... here is the fiddle:

Working Fiddle

El Guapo
  • 5,581
  • 7
  • 54
  • 82
  • 3
    @NicklasA. Behaviour is described here: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-button-element.html -- buttons in forms submit by default and need to be carefully specified if that is not supposed to happen. – Andrew Leach Aug 01 '12 at 13:43
1

I also found this solution. If you set the type attribute to "button" <button type="button">My Button</button> it won't submit. I think not specifying the type by default sets it to submit. So you don't have to change the element to input.

Source: Add regular button inside form that does not perform a submit

Fydo
  • 1,396
  • 16
  • 29
Sergio
  • 11
  • 1