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.
$('form'). bind("keypress", function(e) { if (e. keyCode == 13) { e. preventDefault(); return false; } });
Disallow enter key anywhereon("keydown", "form", function(event) { return event. key != "Enter"; });
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With