jQuery Submit

The submit event triggers whenever a visitor submits a form. There are two ways a form might be submitted - by clicking the Submit button, or by hitting the Enter (Return) key while the cursor is in a text field. Usually when the sumbit event trigers the form is validated for correctness of the fields entered. Once the values are validated, the required action is taken.

It can only be attached to <form> elements.
Here is a simple example that illustrate the usage of the submit trigger.


<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
</head>
<body>

<form action="">
What is Your Name
<input type="text" name="FirstName" value="Michael"><br>
<input type="submit" value="Submit">
</form>
<script>$(document).ready(function(){
  $("form").submit(function(){
    alert("Hi");
      });
})</script>
</body>
</html>




When you click submit button, it triggers the submit event

$("form").submit(function()

Subsequently, an alert message is displayed alert("Hi");

You may like to try this example here.
This example does not do anything that a real world interactive webpage will do. It is an stupid example. Though, it does show the usage of submit event. So let us turn out attention to another example that does something in real world.

This example shows a real world example where a form is presented. You can think of a grade 2 student who is presented with a form to add two numbers and hit submit. Our goal is to check the sum of the two numbers if display messages according to if the result is correct or incorrect.

<html>
<head>
<style>
p { margin:0; color:blue; }
div,p { margin-left:10px; }
span { color:green; }
</style>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
</head>
<body>
<p>What is 4 + 9 ? </p>
<form action="javascript:alert('success!');">
<div>
<input type="text" />
<input type="submit" />
</div>
</form>
<span> Enter Sum and press Submit</span>
<script>
$("form").submit(function() {
if ($("input:first").val() == "13") {
$("span").text("You are correct...").show();
return true;
}
$("span").text("Incorrect ! Please try again").show().fadeOut(2000);
return false;
});
</script>
</body>
</html>




There are few things to notice. First, at the end of the form we have some text with in <span> tag

<span> Enter Sum and press Submit</span>

We will use this text to print different text based upon the validation of the form result. The second thing to notice is the jquery event triggers before the action on the form submission takes place. In our case the action is an alert message that prints success! - but it could potentially be another webpage ( for example success.php) <form action="javascript:alert('success!');">

You may like to try this example here.
As a challenging task you may like to assign the two numbers to be added in a variable and the sum assigned to a third variable. Then you may check the result of the variable in the form validation.