How to call a JavaScript function on submit form

By Saruque Ahamed Mollick

In this JavaScript tutorial, you will learn how to call a JavaScript function on submit form. In easy words, you can say that how to run JavaScript function when someone clicks submit button. This will be very much useful to you. If you are familiar with the term JavaScript form validation then you can understand that this tutorial is related to that.

In a previous tutorial, I have explained with an example Making a simple JavaScript form validator. You can go through this. This post will be helpful to you.

Call a javascript function on submit form

So, I am going to create an HTML form now and then I will create a JavaScript function. Thereafter, I will show you how to call that JavaScript function when the user clicks on the submit button of that form. I hope if you follow what I am going to do here step by step, you will understand easily. Let’s start

Stop form submission using JavaScript preventDefault() Event Method

<form name="myform" action="#" onsubmit="return run_this_function()" method="post">
  
  Full Name:<br>
  <input type="text" name="fullname" id="fullname"><br/>
  
  Phone number:<br>
   <input type="text" name="phone" id="phone"><br/>
  <input type="submit" value="Submit">
  
</form>

Now let’s create run_this_function() JavaScript function

<script>
function run_this_function(){
// your code goes here
}
</script>

So the full code will be like this:

<form name="subscribForm" action="action_page.php" onsubmit="return run_this_function()" method="post">
  
  Full Name:<br>
  <input type="text" name="fullname" id="fullname"><br/>
  
  Phone number:<br>
   <input type="text" name="phone" id="phone"><br/>
  <input type="submit" value="Submit">
  
</form>
<script>
function run_this_function(){
// your code goes here
}
</script>

Now, whenever the user clicks on the submit button the JavaScript function will be called.



You can call any JavaScript function by using this method.

onsubmit event is the event that occurs when the submit button is clicked.

You may also like to read,

How to Access HTML Form Elements in JavaScript Tutorial

Stop form submission using JavaScript preventDefault() Event Method

Leave a Reply

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