2 Demos of How to use JavaScript onsubmit with forms

JavaScript onsubmit

The HTML form’s onsubmit event occurs as an HTML form is submitted. You can attach JavaScript to onsubmit event in order to perform tasks like the form validation.

In this tutorial, we will show you how to use JavaScript onsubmit with different examples, including validation example.

JavaScript form validation example

Following is a form validation example. The demo page asks to fill three textbox fields (First name, last name, and email). The JavaScript validator will check if values in all three fields are entered or not.

If any textbox value is left blank, an alert will be shown, asking to fill the required text field. The JavaScript function is triggered as the form onsubmit event occurs.

JavaScript onsubmit

Experience this example online

As you can see, if any of the fields is left blank, the validator function will throw an alert. The form validation function is called in the form’s onsubmit event.

For that example, we simply thrown the same alert for all fields and focus is set to the first blank field found in form validation.

JavaScript submit form with email validation example

In the above example, though we used an email address for validation but we only checked if the email textbox was empty or filled.

Following is an email validation example where the format of the email will be checked as well. The JavaScript email validation function will check if ‘@’ is entered along with ‘.’ etc. See the demo by clicking the link below:

Experience this example online

You can see in JavaScript form submit example, as you entered an email with the incorrect format (without @ or . or improper letters) and press the button, an alert will be shown by JS function.

Similarly, you can validate other form fields like select dropdowns, radio buttons, check boxes and any other required task by using onsubmit JavaScript event.

Further: JavaScript onclick | javaScript onchange | HTML form

Was this article helpful?

Related Articles

Leave A Comment?