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>
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:
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:
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.
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