How to Use onsubmit Event in JavaScript

02/12/2022

Contents

In this article, you will learn how to use onsubmit event in JavaScript.

What is JavaScript onsubmit?

JavaScript onsubmit is an event that fires when the submit button is clicked.

It can be used to confirm the contents before sending by adding onsubmit to the form tag and specifying the function to be started.
It can also be used in conjunction with preventDefault() to cancel the form’s submission event.

Usage

You can use onsubmit by adding the onsubmit attribute to the form tag and specifying the function to use, or by adding the submit event with eventListener.

To add the onsubmit attribute to the form tag, do as follows.

<form onsubmit="check()">
<input type='submit' value="submit">
</form>
<script>
function check(){
// do something
}
</script>

When adding an event with addEventListener, it is as follows.

<form id="sampleForm">
 <input type='submit' value="submit">
</form>
<script>
const form = document.querySelector("#sampleForm");
form.addEventListener("submit", function(){
 // do something
})
</script>