Forms are where most user interaction happens on a website. jQuery provides a powerful set of events to handle form submissions, detect changes in input fields, and respond when elements gain or lose focus. Mastering these events is key to building modern, user-friendly interfaces.
Here are the four most essential form events in jQuery and when they are triggered:
| Event | Trigger Moment |
|---|---|
submit() |
Fires when a form is submitted (by button or Enter key). |
change() |
Fires when the value of an element is changed (inputs, selects, textareas). |
focus() |
Fires when an element gains focus (clicked or tabbed into). |
blur() |
Fires when an element loses focus. |
The submit() method is used to execute a function when the user tries to Send
a form. Frequently, this is used to perform validation before the data
is actually sent to the server.
$("#myForm").submit(function(event) {
// Check if input is empty
if ($("#name").val() == "") {
alert("Please enter your name!");
// Prevent the form from actually submitting
event.preventDefault();
}
});
These are perfect for giving visual feedback to the user. For example, changing the background color of an input while the user is typing in it.
$("input").focus(function() {
$(this).css("background-color", "#e8f4fb");
});
$("input").blur(function() {
$(this).css("background-color", "#ffffff");
});
The change() event is often used with <select> menus or
checkboxes to trigger an action immediately after the user makes a selection.
$("#country").change(function() {
var selected = $(this).val();
alert("You selected: " + selected);
});
Let's combine multiple events to create a polished experience. We'll check if a password is long enough as the user moves away from the field.
$("#password").blur(function() {
var pass = $(this).val();
if (pass.length < 8) {
$(this).css("border", "2px solid red");
$("#error-msg").text("Password must be 8+ characters");
} else {
$(this).css("border", "2px solid green");
$("#error-msg").text("");
}
});
select() event if you want to perform an
action when the user highlights/selects text inside a <textarea> or
input field.
<form> elements.