Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the evt passed from an onSubmit undefined?

So I'm trying to get the onSubmit to be prevented in a form submission. I have 2 questions.

1) Where is the e parameter being passed in from?

2) Why is e undefined and therefore not correctly preventing the default action? The page refreshes each time which is the action that I'm trying to prevent

<html>
  <head>
  </head>
  <body>
    <form onSubmit={func}>
      <input type='text'/>
      <button type='submit'/>
    </form>
    <script>
      let func = (e) => {
        console.log('BEING CALLED')
        e.preventDefault()
      }
    </script>
  </body>
</html>
like image 888
Darkzuh Avatar asked Feb 06 '23 06:02

Darkzuh


1 Answers

Where is the e parameter being passed in from?

Nowhere

Why is e undefined and therefore not correctly preventing the default action?

Because the function isn't being called.


onSubmit={func}

Your JavaScript function:

  1. Starts a block (which has no practical effect)
  2. Mentions a function name (which has no effect because you didn't call it, combine it with an operator, or anything)
  3. Ends the block

All for a grand total of nothing.


The correct syntax for an onsubmit attribute would be:

onsubmit="func(event);"

… in which you actually call func and you pass it the argument you are trying to pass it. (Intrinsic event attributes get an argument called event automatically).


Binding events with HTML is considered bad practise, and they come with nasty gotchas. It is generally prefered to bind event handlers with JS.

document.querySelector("form")
        .addEventListener("submit", func);

Now func is the event handler itself, and it gets the event object as the first argument because that is what event handlers get.


Note that arrow functions are:

  1. Anonymous, which makes them less useful to work with in debuggers
  2. Capture the current value of this (which is usually unwelcome for event handlers since it stops you using this to get the element the handler was bound to).

Function declarations are generally preferable.

like image 115
Quentin Avatar answered Feb 07 '23 20:02

Quentin