'How to prevent a form input value from disappearing on click in other fields?
The form campaignid input value is automatically filled in when the page is loaded. When I click on the other fields, it reset to default.
What can I do to prevent default and preserve my campaignid input value?
I'm using a third party script to get URL parameters and insert them into campaignid value.
import { Button, FormControl, Input } from "@chakra-ui/react";
import { Field, Form, Formik } from "formik";
import Script from "next/script";
export default function FormikExample() {
return (
<>
<Script src="https://cdn.jsdelivr.net/gh/gkogan/sup-save-url-parameters/sup.min.js" />
<Formik
initialValues={{
name: "",
}}
onSubmit={(values) => {
setTimeout(() => {
fetch(`https://hooks.zapier.com/hooks/catch/3660927/bte5w77/`, {
method: "POST",
body: JSON.stringify(values, null, 2),
}),
3000;
});
}}
>
{(props) => (
<Form id="hero">
<Field name="name">
<FormControl>
{({ field }) => <Input {...field} type="text" id="name" />}
</FormControl>
</Field>
<Field name="email">
<FormControl>
{({ field }) => <Input {...field} type="email" id="email" />}
</FormControl>
</Field>
<Field name="campaignid">
{({ field }) => (
<FormControl isReadOnly>
<Input {...field} type="hidden" value="" id="campaignid" />
</FormControl>
)}
</Field>
<Button id="submited" isLoading={props.isSubmitting} type="submit">
Submit
</Button>
</Form>
)}
</Formik>
</>
);
}
Solution 1:[1]
You need to prevent the default of the submit form. Use prevent default on your submit function, it will stop that behaviour. More info: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
e.preventDefault()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Giovanna PC |
