days
days

Reputation: 75

onSubmit wont fire when using enter key

My question is about react, onSubmit and preventDefault.

I've got a form, which handles between 2 - 4 steps of user input depending on certain cases.

<Form>
{StepRendersHere}
</Form>

The form has a onSubmit event that prevents default (and stopPropagation).

When using the button for "next step" the event fires, and the form is NOT submitted. But when using the enter key, the event is fired, but the form is posted. This results in the site refreshing with the form data as url parameters. The weird thing is that if none of the buttons in the form has type="submit". The onSubmit doesn't even fire on enter key.

isDefaultPrevented returns true in both cases.

Any hints/thoughts on how I can prevent the form from posting when pressing enter? My issue is with Enter key posting the form, despite preventDefault.

Have tried binding the enter key to a event that prevents default, doesn't work. Might have done it the wrong way though.

UPDATE (implementation)

<Form onSubmit={this.inc_step} id="applicationform">
{FormStepRenderedHere}
</Form>

inc_step = e => {
    e.preventDefault();
    e.stopPropagation();
    alert( e.isDefaultPrevented() )
    let new_step = this.state.current_step + 1;
    alert('INSIDE INC STEP');
    if (this.validateForm()) {
        this.setState({
            current_step: new_step
        })
    }
}

UPDATE (FIXED IT)

I found a solution, and want to share if anyone else has the same problem. My solution however might be unique to semantic ui, which i'm using. I solved it by putting as={Form.Group} on the form, mening it wont render as a form, with its standard events, such as enter key submit. Now the enter key does nothing, as I wanted it.

Thank you for the comments!

Upvotes: 1

Views: 1430

Answers (2)

marcusbass323
marcusbass323

Reputation: 11

A much easier way to accomplish this is to add a button element to your form and add the display none css attribute (if you don't want to see the button).

The button automatically adds the ability to use the enter key with onSubmit.

Upvotes: 1

days
days

Reputation: 75

I found a solution, and want to share if anyone else has the same problem. My solution however might be unique to semantic ui, which i'm using. I solved it by putting as={Form.Group} on the form, mening it wont render as a form, with its standard events, such as enter key submit. Now the enter key does nothing, as I wanted it.

So actually not rendering the form as a form to begin with was the solution.

Upvotes: 0

Related Questions