Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent enter key triggering submit

Tags:

reactjs

formik

I am using Formik for a little form in a React app.

The method handleSubmit is triggered when user hits the enter key.

Is there a way to prevent that triggering? I didn't find anything in the formik docs...

Thanks.

like image 576
PeteMeier Avatar asked May 10 '19 09:05

PeteMeier


People also ask

How do I stop form submit on enter key press?

$('form'). bind("keypress", function(e) { if (e. keyCode == 13) { e. preventDefault(); return false; } });

How avoid enter key submit in PHP?

Disallow enter key anywhereon("keydown", "form", function(event) { return event. key != "Enter"; });

How do you stop re submitting a form after clicking back button?

You can check if the user clicked the back button, disable form if true. Another way is by storing a cookie which you check on page load, if it exists you can disable the form.

How do I stop form submit when onclick event return false?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.


1 Answers

You could add an onKeyDown handler like this:

/**
 * Stop enter submitting the form.
 * @param keyEvent Event triggered when the user presses a key.
 */
function onKeyDown(keyEvent) {
  if ((keyEvent.charCode || keyEvent.keyCode) === 13) {
    keyEvent.preventDefault();
  }
}

/**
 * Sample form component.
 */
function Example() {
  return (
    <Formik initialValues={{ name: "" }} onSubmit={() => console.log("Submit")}>
      <Form onKeyDown={onKeyDown}>
        <div>
          <label htmlFor="name">Name</label>
          <Field id="name" name="name" type="text" />
        </div>
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
}

See CodeSandbox example here.

like image 116
Ciarán Tobin Avatar answered Oct 26 '22 22:10

Ciarán Tobin