Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Call a JavaScript Function from an onmouseout Event ?
Next article icon

How to Call a JavaScript Function using an onsubmit Event ?

Last Updated : 10 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

HTML has a form element that is used to get the data from the user and send the data to the server. Before the HTML form sends data to the server, it generates an event called "submit".

This event can be utilized to execute a JavaScript function that can either validate the form data or notify the user of the form submission.

Below are the approaches to call a JavaScript function using an onsubmit event:

Table of Content

  • Using Inline event handler in HTML
  • Using on submit attribute in JavaScript
  • Using addEventListener() method in JavaScript

Using Inline event handler in HTML

Here in the HTML form we pass the javascript function as string to onsubmit parameter of form. when the form submit's, It will run the function.

Syntax:

<form onsubmit="function( )">
<input type="submit">
</form>

Example: To demonstrate running a javascript function that check name validity and create alert message.

HTML
<!DOCTYPE html> <html lang="en">    <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>onsubmit Event</title>     <style>     body{         display: flex;         justify-content: center;         align-items: center;         padding-top: 2rem;     }     h1{         color: #308d46;     }     </style> </head>  <body>      <form         action="/post"        method="post"        onsubmit="formValidation(event)">         <h1>GFG Form Example</h1>         Enter name: <input type="text" name="firstName">         <input              type="submit"             value="Submit">     </form>            <script>         function formValidation(event) {             event             .preventDefault();             let name = event             .target             .firstName.value             if( name.length == 0){                 alert("Enter Valid Name");                 return false;             }             alert ("Form Submitted")         }         </script> </body>    </html> 

Output:

peek
Submit form action using Inline event handler

Using on submit attribute in JavaScript

Instead of assigning the function directly inside the form parameter, we can select the form element using javascript and assign the function to onsubmit parameter from their.

Syntax:

document.getElementById("form").onsubmit = formValidation;

Note: Do not add parenthesis during function assignment.

Example: To demonstrate calling a JavaScript function from an onsubmit event using submit attribute in JavaScript

HTML
<!DOCTYPE html> <html lang="en">    <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>onsubmit Event</title>     <style>     body{         display: flex;         justify-content: center;         align-items: center;         padding-top: 2rem;     }     h1{         color: #308d46;     }     </style> </head>  <body>      <form id="form" action="/post" method="post">         <h1>GFG Form Example</h1>         Enter name: <input type="text" name="firstName">         <input              type="submit"             value="Submit"         >     </form>            <script>         document         .getElementById("form")         .onsubmit = formValidation;          function formValidation(event) {             event             .preventDefault();             let name = event             .target             .firstName.value             if( name.length == 0){                 alert("Enter Valid Name");                 return false;             }             alert ("Form Submitted")         }         </script> </body>    </html> 

Output:

123
Using onsubmit attribute in JavaScript

Using addEventListener() method in JavaScript

Here instead of assigning function to onsubmit parameter of form, we attach event listener to the form element to listen for submit event.

Syntax:

document.getElementById( "form" ).addEventListener( 'submit', formValidation );

Example:To demonstrate calling a JavaScript function from an onsubmit event using event listner method in JavaScript.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>onsubmit Event</title>     <style>         body {             display: flex;             justify-content: center;             align-items: center;             padding-top: 2rem;         }          h1 {             color: #308d46;         }     </style> </head>  <body>      <form id="form" action="/post" method="post">         <h1>GFG Form Example</h1>         Enter name: <input type="text" name="firstName">         <input type="submit" value="Submit">     </form>      <script>         document             .getElementById("form")             .addEventListener('submit', formValidation);          function formValidation(event) {             event.preventDefault();             let name =                 event                     .target                     .firstName                     .value             if (name.length == 0) {                 alert("Enter Valid Name");                 return false;             }             alert("Form Submitted")         }     </script> </body>  </html> 

Output:

007
Using addEventListner method in JavaScript

Next Article
How to Call a JavaScript Function from an onmouseout Event ?
author
mayankratre10
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to Call a JavaScript Function from an onsubmit Event ?
    The onsubmit event attribute in HTML is triggered when a form is submitted. It is also useful for validating form data or performing actions before any submission and ensures better control and validation of user inputs before data is sent. The below methods can be used to call a JavaScript function
    2 min read
  • How to Call a JavaScript Function from an onmouseout Event ?
    The onmouseout event in JavaScript triggers when the mouse pointer leaves an element. This event is commonly used in web development to execute certain functions when a user moves the mouse away from a specific area on the webpage. Below are the approaches to call a JavaScript function from an onmou
    3 min read
  • How to call a JavaScript Function from an onmouseover Event ?
    The onmouseover event in JavaScript is triggered when the mouse pointer moves onto an element, such as a button, image, or text. We will see how to call JavaScript function from an onmouseover event in various ways, like using the onmouseover Attribute and Using Event Listener. Table of Content Usin
    2 min read
  • How to call function from it name stored in a string using JavaScript ?
    In this article, we will call a function from the string stored in a variable. There are two methods to call a function from a string stored in a variable. Using window object methodUsing eval() method Note: The eval() method is older and is deprecated. Method 1: Using the window object. The window
    2 min read
  • Call multiple JavaScript functions in onclick event
    Calling multiple JavaScript functions in an onclick event means executing several functions sequentially when a user clicks an element, like a button. This approach allows you to trigger multiple actions or behaviors with a single click, enhancing interactivity and functionality in web applications.
    2 min read
  • How to solve “Submit is not a function” error in JavaScript ?
    Ever tried to submit a form, by using a JavaScript? But when you tried to submit the form by using JavaScript, you might be getting a “Submit is not a function” error in the code. Well, don’t panic as of yet. This article is being dedicated to solving that problem of yours. So what are we waiting fo
    3 min read
  • How to call a function when content of a div changes using jQuery ?
    The task is to call a function when the content of a div is changed. You can achieve this task by using the in-built method known as .change(). In simple words whenever the field is been changed we call a function that will throw a pop-up. .change(): This method will only trigger when some change oc
    2 min read
  • How to submit a form on Enter button using jQuery ?
    Given an HTML form and the task is to submit the form after clicking the 'Enter' button using jQuery. To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. <!DOCTYPE html> <
    2 min read
  • How to use javascript function in check box?
    Checkboxes are used for instances where a user may wish to select multiple options, such as in the instance of a "check all that apply" question, in forms. HTML Checkboxes Selected. A checkbox element can be placed onto a web page in a pre-checked fashion by setting the checked attribute with a "yes
    2 min read
  • How to Call a JavaScript Function from Chrome Console ?
    One can call a JavaScript Function from the Chrome Console. We will learn how can we call the function in the console that is written in JavaScript. Steps to call a JavaScript Function from Chrome ConsoleOpen the Chrome ConsoleYou can open the Chrome Console by right-clicking on your webpage, select
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences