I have a form I'm submitting with javascript (with react specifically, but I don't think it matters for the purposes of the question).
The form has a few inputs and two buttons. One is a normal submit button, and one triggers a secondary action.
Crucially, the secondary button comes first in the HTML order and I can't change this (not even with flexbox order).
Frustratingly, this seems to mean that when the user finishes typing and hits enter, the secondary button gets triggered.
I'm listening to the form's submit event for the primary action, which is what I would have thought hitting enter would trigger. The secondary button has a click event listener on it.
How can I make it so the form's primary action gets triggered on pressing enter?
The secondary action should only happen if the user clicks that button or explicitly focuses onto it and hits enter.
You can think of the form as structured like this:
<form onSubmit={primaryAction}>
<input ... />
<input ... />
<button onClick={secondaryAction}>Second action</>
<button>Submit</button>
</form>
I've also tried:
- Reorganising the HTML so that the primary button comes first in the HTML order. Some sources say this works but it's not an option because I'm using absolute positioning on this form and futzing with the HTML order (even with flexbox order) breaks the layout.
- Using the submitter property on the form's submit event. This doesn't seem to work cross-browser yet.
A good example of what I'm trying to achieve is Deliveroo's home page. On the version I see there's a form with one text input and two actions (use my current location and search). When you hit enter, it's the primary (search) action that gets triggered despite the button for the secondary coming first in the html order.