0

I have a form which has an onSubmit I want to run this function every time the user changes a value in the input field so I have attached this little function on the form

       onChange={() => {
         formRef.current?.submit();
       }}

My problem is that now when I change values in the input the page refreshes even trought I have e.preventDefault(); on my onSubmit

        onSubmit={(e) => {
          e.preventDefault();
    ...

Thank you for reading.

LAYTOR
  • 381
  • 4
  • 12
  • Does this answer your question? [ReactJS: how to trigger form submit event from another event](https://stackoverflow.com/questions/28904875/reactjs-how-to-trigger-form-submit-event-from-another-event) – Andy Ray Jun 06 '23 at 03:37
  • I have tried formRef.current?.dispatchEvent(new Event("submit")) but it doesn't do anything when I console.log it I receive a value of true but again nothing is happening – LAYTOR Jun 06 '23 at 03:40

1 Answers1

0

I used to have this problem as well. I've added specific typing for the event parameter, which resolved my problems so far. I don't understand why you want to perform a onSubmit on every change. Personally, I would run the onSubmit if the element loses focus, but to answer your question:

Replace your onSubmit function with this:

onSubmit=((e: React.FormEvent<HTMLInputElement>): void => {
  e.preventDefault();
  // ...
})
S. Kok
  • 23
  • 6
  • I had added a specific types but it hasn't solved my problem – LAYTOR Jun 14 '23 at 23:14
  • What is the error you are receiving? Or what does not go as expected? Does it still redirect to another page? – S. Kok Jun 16 '23 at 02:08
  • Yes, nothing had changed in behavior of both, formRef.current?.submit(); and formRef.current?.dispatchEvent(new Event("submit")) I had found a work around but am still interested in the solution for my problem if there is one. – LAYTOR Jun 17 '23 at 02:43
  • Did you console.log() the formRef.current? – S. Kok Jun 18 '23 at 13:15