jQuery - .submit() as an event handler
.submit() as an event handler
Used to run code when a form is submitted.
Syntax
$("form").submit(function(){
// code to execute on submit
});
Example
<form id="myForm">
<input type="text" required>
<button type="submit">Submit</button>
</form>
<script>
$("#myForm").submit(function(){
alert("Form submitted!");
});
</script>
What happens?
-
The function runs when the user clicks submit or presses Enter
-
The form will submit normally unless prevented
2️⃣ Preventing form submission using .submit()
To stop the form from submitting (common in validation or AJAX):
Example
$("#myForm").submit(function(e){
e.preventDefault(); // stops form submission
alert("Submission prevented");
});
Why use this?
-
Client-side validation
-
AJAX form submission
-
Prevent page reload
3️⃣ .submit() to trigger form submission
You can also manually submit a form.
Example
$("#myForm").submit();
Use cases
-
Submit form after validation
-
Submit form from another button or event
4️⃣ .submit() vs HTML submit
| Method | Description |
|---|---|
.submit() |
jQuery method |
<button type="submit"> |
HTML submit |
.submit() event |
Attach logic |
.submit() trigger |
Force submit |
5️⃣ Common interview points
-
.submit()works only with<form>elements -
e.preventDefault()is used to stop default behavior -
Often used with AJAX
-
Triggered by Enter key or submit button
6️⃣ Simple real-world example (validation)
$("#myForm").submit(function(e){
if($("#name").val() === ""){
alert("Name is required");
e.preventDefault();
}
});