Form Events
Handle submit, change, focus, and blur on form controls.
Syntax
$(form).on("submit", function (e) { e.preventDefault(); ... });Forms fire their own events you can hook into:
submit— the form is being sent.change— an input value changed and lost focus.focus/blur— a field gains / loses focus.
Call e.preventDefault() inside a submit handler to stop the page from reloading so you can handle it yourself.
Example
Loading editor…
Press Run to see the result.
When to use it
- A registration form validates the email field on blur so the error appears only after the user leaves the input.
- A live character counter updates on every input event to show how many characters remain in a tweet field.
- A multi-step form listens for the submit event to prevent the default POST and send data via AJAX instead.
More examples
Validate email on blur
blur fires when the input loses focus, giving feedback after the user finishes typing rather than mid-entry.
<input id="email" type="email" placeholder="Email" />
<p id="err" style="color:red;display:none">Invalid email</p>
<script>
$(function () {
$("#email").on("blur", function () {
var ok = /\S+@\S+\.\S+/.test($(this).val());
$("#err").toggle(!ok);
});
});
</script>Live character counter on input
The input event fires on every keystroke and paste, keeping the counter accurate and coloring it red when near the limit.
<textarea id="tweet" maxlength="280" rows="4"></textarea>
<p><span id="rem">280</span> characters remaining</p>
<script>
$(function () {
$("#tweet").on("input", function () {
var left = 280 - $(this).val().length;
$("#rem").text(left).css("color", left < 20 ? "red" : "");
});
});
</script>Intercept form submit for AJAX
e.preventDefault() stops the page reload; .serialize() encodes form fields for the AJAX POST request.
<form id="contact">
<input name="name" placeholder="Name" />
<button type="submit">Send</button>
</form>
<p id="msg"></p>
<script>
$(function () {
$("#contact").on("submit", function (e) {
e.preventDefault();
$.post("/api/contact", $(this).serialize(), function () {
$("#msg").text("Message sent!");
});
});
});
</script>
Discussion