Quick Reach
jQuery submit method
As web developer one needs to use HTML forms in many scenarios, to collect user information for different purposes.
As a user clicks on Submit button, a Submit event occurs. jQuery provided submit() method to handle submit event where a function can be attached to perform certain actions e.g. checking form fields before submitting to the database.
This chapter guides through the syntax of the submit() method of jQuery and its usage by an example.
Syntax of using the submit method
This is how you may use the submit jQuery method:
$(selector).submit()
Using submit method with function
$(selector).submit(function)
As this method works only with forms’ elements, so selector = form or form’s elements where you need to handle the submit event.
Example of using submit() method
After opening the demo page, enter the test information in the form fields and press the “submit now” button. The submit event will occur where the submit method is used to trigger an alert:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
<html>
<head>
<script src=“http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”>
</script>
<script>
$(document).ready(function(){
$(“#submittest”).submit(function(){
alert(“Submit event occured”);
});
});
</script>
</head>
<body>
<form id=“submittest” action=“#”>
First name:
<input type=“text” name=“FName”><br>
Last name:
<input type=“text” name=“LName”><br>
<input type=“submit” value=“submit now”>
</form>
</body>
</html>
|
Example of Submit() to prevent submit if First name field is empty
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
<html>
<head>
<script src=“http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”>
</script>
<script>
$(document).ready(function(){
$(“#submittest”).submit(function(event){
alert(“Submit event occured”);
if (document.getElementById(“FName”).value==”){
event.preventDefault();
alert(“”);
}
else{
alert(“Not empty”);
}
});
});
</script>
</head>
<body>
<form id=“submittest” action=“#”>
First name:
<input type=“text” id=“FName”><br>
Last name:
<input type=“text” id=“LName”><br>
<input type=“submit” value=“submit now”>
</form>
</body>
</html>
|
Read more: jQuery preventdefault
Leave A Comment?