Form Events
Focus
The focus event fires the moment a user clicks into or tabs onto a form control, making it useful for showing hints or highlighting the active field.
Example: Focus
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="name" type="text">
<script>
$("#name").on("focus", function() {
console.log("Field focused");
});
</script>
</body>
</html>
Blur
The blur event runs when a form control loses focus, which is the natural place to run validation -- checking a field's value right after the user has finished with it, rather than on every keystroke.
Example: Blur
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="email" type="text">
<script>
$("#email").on("blur", function() {
console.log("Validate:", $(this).val());
});
</script>
</body>
</html>
Change
The change event fires when a control's value has been altered and the user moves away from it, so for a text input it waits until blur, while for a checkbox or select it fires as soon as the selection changes.
Example: Change
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<select id="color"><option>Red</option><option>Blue</option></select>
<script>
$("#color").on("change", function() {
console.log("Selected:", $(this).val());
});
</script>
</body>
</html>
Submit
The submit event fires when a form is submitted, either by clicking a submit button or pressing Enter in a field, and is the standard place to run final validation or call event.preventDefault() to stop a normal page reload.
Example: Submit
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<form id="myForm"><button type="submit">Send</button></form>
<script>
$("#myForm").on("submit", function(event) {
event.preventDefault();
console.log("Form submitted");
});
</script>
</body>
</html>
Input
The input event fires immediately on every keystroke or value change, even before the field loses focus, making it the right choice for live character counters or instant search-as-you-type behavior.
Example: Input
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="search" type="text"><p id="count"></p>
<script>
$("#search").on("input", function() {
$("#count").text($(this).val().length + " characters");
});
</script>
</body>
</html>
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: