Categories
JavaScript Answers

How to fix form onsubmit not working with JavaScript?

Spread the love

Sometimes, we want to fix form onsubmit not working with JavaScript.

In this article, we’ll look at how to fix form onsubmit not working with JavaScript.

How to fix form onsubmit not working with JavaScript?

To fix form onsubmit not working with JavaScript, we can set the form’s onsubmit property to a function that’s run when we click the submit button.

For instance, we write:

<form>
  <input type="file" name="file">
  <input type="submit">
</form>

to add a form.

We add the submit button for the form with <input type="submit">.

Next, we write:

const form = document.querySelector('form')
form.onsubmit = (e) => {
  e.preventDefault()
  console.log('submitted')
}

to select the form with querySelector.

And then we set form.onsubmit to a function that calls preventDefault to stop the default server side behavior and log 'submitted'.

Therefore, when we click on Submit, we see 'submitted' logged.

Conclusion

To fix form onsubmit not working with JavaScript, we can set the form’s onsubmit property to a function that’s run when we click the submit button.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *